最近遇到这个问题:
假设有一个我要处理的列表:
process_list=["/test/fruit/apple","/test/fruit/pineapple","/test/fruit/banana","/test/tech/apple-pen","/test/animal/python","/test/animal/penguin"]
我想使用另一个列表排除某些内容,例如:
exclude_list=["apple","python"]
在我将 exclude_list 应用于它之后,process_list 应该是这样的(任何包含 sub 的 process_list 项目:
["/test/fruit/banana","/test/animal/penguin","/test/fruit/pineapple"]
或者如果 exclude_list 是:
exclude_list=["pen","banana"]
应用过滤器后,process_list 应该是这样的:
["/test/fruit/apple","/test/fruit/pineapple","/test/animal/python"]
所以我一开始尝试的是:
for item in exclude_list:
for name in (process_list):
if item in name:
process_list.remove(name)
当然这是行不通的,因为在使用 for
循环遍历列表的同时从列表中删除元素是不允许的。该代码仅删除了第一个匹配项,然后停止。
然后我想出了一个方法来用另一个列表来做到这一点:
deletion_list=[] #Track names that need to be deleted
for item in exclude_list:
for name in (process_list):
if item in name:
deletion_list.append(name)
# A list comprehension
process_list=[ x for x in process_list if x not in deletion_list ]
它有效,但我的直觉告诉我可能有更优雅的方法。现在需要另一个列表来存储需要删除的名称。有什么想法吗?
最佳答案
您可以使用 all()
来使用列表理解 表达式过滤为:
# Here: `p` is the entry from `process_list`
# `e` is the entry from `exclude_list`
>>> [p for p in process_list if all(e not in p for e in exclude_list)]
['/test/fruit/banana', '/test/animal/penguin']
关于您的声明:
Of course this didn't work because removing elements from the list while iterating over it using a for loop is not permitted. The code only removed the first match and then stopped.
您可以像这样迭代列表的副本:
for item in list(exclude_list): # OR, for item in exclude_list[:]:
# ^-- Creates new copy ----------------------------^
关于python - 删除列表中没有出现在另一个列表中的子字符串的项目的优雅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40791002/