[英]Remove item from list if in another list (lists of list)
我有一个看起来像这样的列表
a = [('Eth1', 'desc', 'date'), ('Eth2', 'dest', 'date'), ('Eth3', 'dest', 'date')]
我有另一个列表:
b = = ['Eth1', 'Eth2']
我想删除a中出现的所有b及其相应的数据,所以我得到的那一刻
c = list(set(a) - set(b))
print c
我希望c看起来像这样
c = ['Eth3', 'dest', 'date']
但它只是以不同的顺序打印列表,就像这样
[('Eth2', 'dest', 'date'), ('Eth1', 'desc', 'date'), ('Eth3', 'dest', 'date')]
最好的方法是什么?
你需要一个列表理解:
In [4]: [tup for tup in a if tup[0] not in b]
Out[4]: [('Eth3', 'dest', 'date')]
请注意,您不能在此处使用set
的操作,因为您不想完全比较元组,而是首先比较元组(然后根据它删除整个元组)。
此外,如果你的名单更长,你最好使用set
来保存b
的项目。 原因是成员资格检查是O(1)成套。
为了完整起见,这里也是一个功能性解决方案(在这种情况下不推荐,特别是如果您希望结果为列表):
In [7]: list(filter(lambda x: x[0] not in b, a))
Out[7]: [('Eth3', 'dest', 'date')]
您也可以使用filter
功能:
a = [('Eth1', 'desc', 'date'), ('Eth2', 'dest', 'date'), ('Eth3', 'dest', 'date')]
b = ['Eth1', 'Eth2']
res = list(filter(lambda i: i[0] not in b, a))
print(res)
输出:
[('Eth3', 'dest', 'date')]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.