我想根据data
中的项目过滤drop
。
data = [
['Basket', 'NBA ET', 'Kobe'],
['Basket', 'NCAA', 'Shaq'],
['Basket', 'ENG', 'Shaq'],
]
drop = ['NBA', 'NCAA']
因为我希望列出NBA ET
的列表也被忽略了,所以它必须超越:
filtered = [d for d in data if d[1] not in drop] # assume d[1] will hold
我需要的是:
# pseudocode
filtered = [d for d in data if _ not in d[1] for _ in drop]
但我永远记不起语法。
对于记录,filtered
应该会产生[['Basket', 'ENG', 'Shaq']]
答案 0 :(得分:2)
您可以使用any()
并在空白处拆分字符串:
filtered = [d for d in data if not any(dropped in d[1].split() for dropped in drop)]
如果您将drop
设为设置,只需测试一个十字路口:
drop = set(drop)
filtered = [d for d in data if not drop.intersection(d[1].split())]
后者应该更大,drop
变得更好。
演示:
>>> data = [
... ['Basket', 'NBA ET', 'Kobe'],
... ['Basket', 'NCAA', 'Shaq'],
... ['Basket', 'ENG', 'Shaq'],
... ]
>>> drop = ['NBA', 'NCAA']
>>> [d for d in data if not any(dropped in d[1].split() for dropped in drop)]
[['Basket', 'ENG', 'Shaq']]
>>> drop = set(drop)
>>> [d for d in data if not drop.intersection(d[1].split())]
[['Basket', 'ENG', 'Shaq']]
答案 1 :(得分:1)
[row for row in data if not any(league in row[1].split() for league in drop)]
# [['Basket', 'ENG', 'Shaq']]