我在Python中有两个列表:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
假设每个列表中的元素都是唯一的,我想用第一个列表中的项创建第三个列表,这些项不在第二个列表中:
temp3 = ['Three', 'Four']
有没有没有周期和检查的快速方法?
我在Python中有两个列表:
temp1 = ['One', 'Two', 'Three', 'Four']
temp2 = ['One', 'Two']
假设每个列表中的元素都是唯一的,我想用第一个列表中的项创建第三个列表,这些项不在第二个列表中:
temp3 = ['Three', 'Four']
有没有没有周期和检查的快速方法?
当前回答
我想要一个能够使用两个列表并能做diff in bash所做的事情的东西。因为当你搜索“python diff two lists”时,这个问题首先会弹出,而且不是很具体,所以我会把我想到的贴出来。
使用difflib中的SequenceMather,你可以像diff一样比较两个列表。其他答案都不会告诉你差异发生的位置,但这个答案可以。有些答案只给出了一个方向上的差异。有些元素会重新排序。有些公司不处理副本。但是这个解决方案让你在两个列表之间有了真正的区别:
a = 'A quick fox jumps the lazy dog'.split()
b = 'A quick brown mouse jumps over the dog'.split()
from difflib import SequenceMatcher
for tag, i, j, k, l in SequenceMatcher(None, a, b).get_opcodes():
if tag == 'equal': print('both have', a[i:j])
if tag in ('delete', 'replace'): print(' 1st has', a[i:j])
if tag in ('insert', 'replace'): print(' 2nd has', b[k:l])
这个输出:
both have ['A', 'quick']
1st has ['fox']
2nd has ['brown', 'mouse']
both have ['jumps']
2nd has ['over']
both have ['the']
1st has ['lazy']
both have ['dog']
当然,如果您的应用程序做出了与其他答案相同的假设,那么您将从中受益最大。但如果你正在寻找一个真正的差异功能,那么这是唯一的方法。
例如,其他答案都无法处理:
a = [1,2,3,4,5]
b = [5,4,3,2,1]
但这一个有:
2nd has [5, 4, 3, 2]
both have [1]
1st has [2, 3, 4, 5]
其他回答
假设我们有两个列表
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
试试这个:
temp3 = set(temp1) - set(temp2)
这可能比马克的清单理解还要快:
list(itertools.filterfalse(set(temp2).__contains__, temp1))
如果散差表的元素是排序和集合的,你可以使用朴素方法。
list1=[1,2,3,4,5]
list2=[1,2,3]
print list1[len(list2):]
或者使用本机set方法:
subset=set(list1).difference(list2)
print subset
import timeit
init = 'temp1 = list(range(100)); temp2 = [i * 2 for i in range(50)]'
print "Naive solution: ", timeit.timeit('temp1[len(temp2):]', init, number = 100000)
print "Native set solution: ", timeit.timeit('set(temp1).difference(temp2)', init, number = 100000)
朴素解:0.0787101593292
本机集解决方案:0.998837615564
单线版arulmr解决方案
def diff(listA, listB):
return set(listA) - set(listB) | set(listB) -set(listA)