我有两个python列表:
a = [('when', 3), ('why', 4), ('throw', 9), ('send', 15), ('you', 1)]
b = ['the', 'when', 'send', 'we', 'us']
Run Code Online (Sandbox Code Playgroud)
我需要过滤掉与b中类似的所有元素.就像在这种情况下,我应该得到:
c = [('why', 4), ('throw', 9), ('you', 1)]
Run Code Online (Sandbox Code Playgroud)
什么应该是最有效的方法?
Oct*_*ipi 10
列表理解将起作用.
a = [('when', 3), ('why', 4), ('throw', 9), ('send', 15), ('you', 1)]
b = ['the', 'when', 'send', 'we', 'us']
filtered = [i for i in a if not i[0] in b]
>>>print(filtered)
[('why', 4), ('throw', 9), ('you', 1)]
Run Code Online (Sandbox Code Playgroud)
列表理解应该有效:
c = [item for item in a if item[0] not in b]
Run Code Online (Sandbox Code Playgroud)
或者使用字典理解:
d = dict(a)
c = {key: value for key in d.iteritems() if key not in b}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11004 次 |
| 最近记录: |