我有路径列表作为字符串
>>> p = ['/path/one/foo.txt', '/path/two/foo.txt', '/path/three/foo.txt', '/path/four/foo.txt
]
我知道我可以使用类似的方法从列表中删除包含单词的条目
>>> p = [x for x in p if 'two' not in x]
>>> p
['/path/one/foo.txt', '/path/three/foo.txt', '/path/four/foo.txt']
但是,这似乎不起作用
>>> p = [x for x in p if 'two' or 'three' not in x]
>>> p
['/path/one/foo.txt', '/path/two/foo.txt', '/path/three/foo.txt', '/path/four/foo.txt
]`
如何删除p
中包含two
或three
的所有条目?
请注意,我是从字典中的单独键中提取值two
和three
,因此创建单个列表可能并不简单。
答案 0 :(得分:4)
尝试这个:
p = [x for x in p if 'two' not in x and 'three' not in x]
答案 1 :(得分:2)
您可以将all
与生成器表达式一起使用:
values = ('two', 'three')
p = [x for x in p if all(i not in x for i in values)]
一个更好的主意是提取特定的文件夹并将其与set
进行比较。您的示例很简单,因为您只对第二个目录感兴趣:
values = {'two', 'three'}
L = ['/path/one/foo.txt', '/path/two/foo.txt',
'/path/three/foo.txt', '/path/four/foo.txt']
res = [i for i in L if i.split('/')[2] not in values]
print(res)
['/path/one/foo.txt', '/path/four/foo.txt']
答案 2 :(得分:1)
p = [x for x in p if 'two' not in x and 'three' not in x]
在Python中,您有两个单独的布尔语句:'two' in x
和'three' in x
。您使用的语法无法正常工作,因为Python无法将该语法识别为两个单独的布尔语句。
答案 3 :(得分:1)
使用正则表达式。 -> re.search(r"(two|three)", x)
演示:
import re
p = ['/path/one/foo.txt', '/path/two/foo.txt', '/path/three/foo.txt', '/path/four/foo.txt']
p = [x for x in p if not re.search(r"(two|three)", x)]
print(p)
输出:
['/path/one/foo.txt', '/path/four/foo.txt']
答案 4 :(得分:1)
@ afg1997 ,您还可以继续使用自己的方法,只需将或替换为和,并对代码进行一些修改即可
>>> p = ['/path/one/foo.txt', '/path/two/foo.txt', '/path/three/foo.txt', '/path/four/foo.txt']
>>>
>>> [x for x in p if not 'two' in x and not 'three' in x]
['/path/one/foo.txt', '/path/four/foo.txt']
>>>