我在Python中有两个列表:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
假设每个列表中的元素都是唯一的,我想用第一个列表中的项创建第三个列表,这些项不在第二个列表中:
temp3 = ['Three', 'Four']
有没有没有周期和检查的快速方法?
我在Python中有两个列表:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
假设每个列表中的元素都是唯一的,我想用第一个列表中的项创建第三个列表,这些项不在第二个列表中:
temp3 = ['Three', 'Four']
有没有没有周期和检查的快速方法?
当前回答
最简单的方法,
使用设置().difference(设置())
list_a = [1,2,3]
list_b = [2,3]
print set(list_a).difference(set(list_b))
答案设置([1])
可以打印为列表,
print list(set(list_a).difference(set(list_b)))
其他回答
以下是@SuperNova的回答的修改版本
def get_diff(a: list, b: list) -> list:
return list(set(a) ^ set(b))
我知道这个问题已经得到了很好的答案,但我希望使用numpy添加以下方法。
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
list(np.setdiff1d(temp1,temp2))
['Four', 'Three'] #Output
两个列表(例如list1和list2)之间的差异可以使用下面的简单函数找到。
def diff(list1, list2):
c = set(list1).union(set(list2)) # or c = set(list1) | set(list2)
d = set(list1).intersection(set(list2)) # or d = set(list1) & set(list2)
return list(c - d)
or
def diff(list1, list2):
return list(set(list1).symmetric_difference(set(list2))) # or return list(set(list1) ^ set(list2))
通过使用上述函数,可以使用diff(temp2, temp1)或diff(temp1, temp2)找到差异。两者都会给出结果['Four', 'Three']。你不需要担心列表的顺序或者先给出哪个列表。
Python文档参考
我更喜欢使用转换到集,然后使用“差分()”函数。完整的代码是:
temp1 = ['One', 'Two', 'Three', 'Four' ]
temp2 = ['One', 'Two']
set1 = set(temp1)
set2 = set(temp2)
set3 = set1.difference(set2)
temp3 = list(set3)
print(temp3)
输出:
>>>print(temp3)
['Three', 'Four']
这是最容易理解的,而且在将来,如果你处理大型数据,将其转换为集合将删除不需要的重复项。希望能有所帮助;-)
如果要删除列表a中存在于列表b中的所有值。
def list_diff(a, b):
r = []
for i in a:
if i not in b:
r.append(i)
return r
list_diff([1、2、2],[1])
结果(2,2):
or
def list_diff(a, b):
return [x for x in a if x not in b]