根据字符串提取路径名

extract path name based on a string

下面是我的例子:

from itertools import zip_longest

test2 = ['register/adam/users_photo3.jpg', 'register/adam/users_photo4.jpg', 
'register/justin/users_photo1.jpg', 'register/justin/users_photo2.jpg', 
'register/adam/users_photo3.jpg', 'register/adam/users_photo4.jpg', 
'register/justin/users_photo1.jpg', 'register/justin/users_photo2.jpg', 
'register/steve/users_photo1.jpg', 'register/steve/users_photo2.jpg', 
'register/justin/users_photo1.jpg', 'register/justin/users_photo2.jpg', 
'register/steve/users_photo1.jpg', 'register/steve/users_photo2.jpg', 
'register/justin/users_photo1.jpg', 'register/justin/users_photo2.jpg']

test = ["justin","adam"]


filter_list = []
for p,q in zip_longest(test,list_of_files):
    for r in list_of_files:
        if str(p) in r:
            filter_list.append(r)       


testmain=[p for p,r in zip_longest(test2,filter_list) if str(r) not in str(p)]
print(testmain) 

我想要测试的相反输出 url。例如“史蒂夫”url 需要作为输出! 需要的输出:输出中需要的所有史蒂夫url。

希望我澄清了自己并得到一些回应,谢谢。

我不确定你为什么压缩这些名字。您可以使用 not any() 来测试没有匹配项:

test2 = ['register/adam/users_photo3.jpg', 'register/adam/users_photo4.jpg', 
'register/justin/users_photo1.jpg', 'register/justin/users_photo2.jpg', 
'register/adam/users_photo3.jpg', 'register/adam/users_photo4.jpg', 
'register/justin/users_photo1.jpg', 'register/justin/users_photo2.jpg', 
'register/steve/users_photo1.jpg', 'register/steve/users_photo2.jpg', 
'register/justin/users_photo1.jpg', 'register/justin/users_photo2.jpg', 
'register/steve/users_photo1.jpg', 'register/steve/users_photo2.jpg', 
'register/justin/users_photo1.jpg', 'register/justin/users_photo2.jpg']

test = ["justin","adam"]

[url for url in test2 if not any(name in url for name in test)]

这会给你:

'[register/steve/users_photo1.jpg',
 'register/steve/users_photo2.jpg',
 'register/steve/users_photo1.jpg',
 'register/steve/users_photo2.jpg']

如果 test 很长,这些可能是一些优化,但这应该适用于正常大小的输入。

我会使用列表理解和 re.search:

test2 = ['register/adam/users_photo3.jpg', 
    'register/adam/users_photo4.jpg', 
    'register/justin/users_photo1.jpg', 
    'register/justin/users_photo2.jpg', 
    'register/adam/users_photo3.jpg', 
    'register/adam/users_photo4.jpg', 
    'register/justin/users_photo1.jpg', 
    'register/justin/users_photo2.jpg', 
    'register/steve/users_photo1.jpg', 
    'register/steve/users_photo2.jpg', 
    'register/justin/users_photo1.jpg', 'register/justin/users_photo2.jpg', 
    'register/steve/users_photo1.jpg', 'register/steve/users_photo2.jpg', 
    'register/justin/users_photo1.jpg', 'register/justin/users_photo2.jpg']

test = ["justin", "adam"]
regex = r'/(?:' + '|'.join(test) + r')/'
output = [x for x in test2 if not re.search(regex, x)]
print(output)

这会打印:

['register/steve/users_photo1.jpg', 'register/steve/users_photo2.jpg',
 'register/steve/users_photo1.jpg', 'register/steve/users_photo2.jpg']