我在Python中有两个列表:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
假设每个列表中的元素都是唯一的,我想用第一个列表中的项创建第三个列表,这些项不在第二个列表中:
temp3 = ['Three', 'Four']
有没有没有周期和检查的快速方法?
我在Python中有两个列表:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
假设每个列表中的元素都是唯一的,我想用第一个列表中的项创建第三个列表,这些项不在第二个列表中:
temp3 = ['Three', 'Four']
有没有没有周期和检查的快速方法?
当前回答
假设我们有两个列表
list1 = [1, 3, 5, 7, 9]
list2 = [1, 2, 3, 4, 5]
从上面两个列表中我们可以看到,list2中有第1、3、5项,而第7、9项不存在。另一方面,第1、3、5项在list1中存在,第2、4项不存在。
返回包含项目7,9和2,4的新列表的最佳解决方案是什么?
以上所有答案都找到了解,现在什么是最优的?
def difference(list1, list2):
new_list = []
for i in list1:
if i not in list2:
new_list.append(i)
for j in list2:
if j not in list1:
new_list.append(j)
return new_list
与
def sym_diff(list1, list2):
return list(set(list1).symmetric_difference(set(list2)))
利用时间,我们可以看到结果
t1 = timeit.Timer("difference(list1, list2)", "from __main__ import difference,
list1, list2")
t2 = timeit.Timer("sym_diff(list1, list2)", "from __main__ import sym_diff,
list1, list2")
print('Using two for loops', t1.timeit(number=100000), 'Milliseconds')
print('Using two for loops', t2.timeit(number=100000), 'Milliseconds')
返回
[7, 9, 2, 4]
Using two for loops 0.11572412995155901 Milliseconds
Using symmetric_difference 0.11285737506113946 Milliseconds
Process finished with exit code 0
其他回答
如果你遇到TypeError: unhashable type: 'list',你需要将列表或集转换为元组。
set(map(tuple, list_of_lists1)).symmetric_difference(set(map(tuple, list_of_lists2)))
参见如何比较python中的列表/集列表?
单线版arulmr解决方案
def diff(listA, listB):
return set(listA) - set(listB) | set(listB) -set(listA)
如果要删除列表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]
以下是@SuperNova的回答的修改版本
def get_diff(a: list, b: list) -> list:
return list(set(a) ^ set(b))
最简单的方法,
使用设置().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)))