得到两个列表之间的差异Python中有两个列表,如下所示:temp1 = ['One', 'Two', 'Three', 'Four']temp2 = ['One', 'Two']我需要创建第三个列表,其中包含第一个列表中没有出现在第二个列表中的项目。从我要得到的例子来看:temp3 = ['Three', 'Four']有没有循环和检查的快速方法?
3 回答
蝴蝶刀刀
TA贡献1801条经验 获得超8个赞
In [5]: list(set(temp1) - set(temp2))Out[5]: ['Four', 'Three']
In [5]: set([1, 2]) - set([2, 3])Out[5]: set([1])
set([1, 3])
set([1, 3])
set([1, 2]).symmetric_difference(set([2, 3]))
.
ibeautiful
TA贡献1993条经验 获得超5个赞
比O(n*m)性能快。 保持输入列表的顺序。
s = set(temp2)temp3 = [x for x in temp1 if x not in s]
性能试验
import timeit init = 'temp1 = list(range(100)); temp2 = [i * 2 for i in range(50)]'print timeit.timeit('list(set(temp1) - set(temp2))', init, number = 100000)print timeit.timeit('s = set(temp2);[x for x in temp1 if x not in s]', init, number = 100000)print timeit. timeit('[item for item in temp1 if item not in temp2]', init, number = 100000)
4.34620224079 # ars' answer4.2770634955 # This answer30.7715615392 # matt b's answer
init = ''' temp1 = [str(i) for i in range(100000)] temp2 = [str(i * 2) for i in range(50)] '''
11.3836875916 # ars' answer3.63890368748 # this answer (3 times faster!)37.7445402279 # matt b's answer
添加回答
举报
0/150
提交
取消