如何检查list1是否包含list2中的某些元素?
我想从list1中删除几个字符串,所以我把它们放到了list2里,但我就是找不到方法让它工作。
list1 = ['abc', 'def', '123']
list2 = ['def', 'xyz', 'abc'] # stuff to delete from list1
我想把'abc'和'def'从list1中去掉,这样list1里就只剩下我需要的东西了。
4 个回答
0
这里有一个更简短的答案,使用了内置的集合方法:
list1 = ['abc', 'def', '123']
list2 = ['def', 'xyz', 'abc']
set1 = set(list1)
set2 = set(list2)
print(set1.difference(set2)))
引用上面的文档内容:
“返回一个新的集合,这个集合里的元素是在这个集合中但不在其他集合里的。”
0
list1 = set(['abc', 'def', '123'])
list2 = set(['def', 'xyz', 'abc'])
# here result will contain only the intersected element
# so its very less.
result = set(filter(set(list1).__contains__, list2))
newlist = list()
for elm in list1:
if elm not in result:
newlist.append(elm)
print newlist
输出结果:
['123']
1
如果你的 list1
里没有重复的元素(或者你想要去掉重复的元素),你可以使用下面这个方法:
list1 = set(['abc', 'def', '123'])
list2 = set(['def', 'xyz', 'abc'])
print(list(list1 - list2))
6
你可以通过使用列表推导式来过滤数据,像这样:
set2, list1 = set(['def', 'xyz', 'abc']), ['abc', 'def', '123']
print [item for item in list1 if item not in set2]
# ['123']
我们把 list2
的元素转换成一个集合,因为这样查找的速度更快。
这个逻辑和这样写是类似的:
result = []
for item in list1:
if item not in set2:
result.append(item)