比较两个列表的有效方法,记住每个唯一元素的原点

时间:2016-08-07 16:10:23

标签: python list python-3.x

给定此示例,该示例在可用于告知元素源

时找到唯一元素
source_list = ["one", "two", "three", "four", "five"]
diff_list = ["zero", "one", "two", "three", "four", "six", "seven"]

source_unique = []
diff_unique = []

for entry in source_list:
    if entry not in diff_list:
        source_unique.append(entry)

for entry in diff_list:
    if entry not in source_list:
        diff_unique.append(entry)

print("Unique elements in source_list: {0}".format(source_unique))
print("Unique elements in diff_list: {0}".format(diff_unique))

###
# Unique elements in source_list: ['five']
# Unique elements in diff_list: ['zero', 'six', 'seven']

有没有更有效的方法来做这个而不是使用两个额外的列表和所有这些东西?主要任务是能够告诉元素'原点。

3 个答案:

答案 0 :(得分:4)

使用difference并将其>>> s1, s2 = set(source_list), set(diff_list) >>> s1.difference(s2) {'five'} >>> s2.difference(s1) {'seven', 'six', 'zero'} 复杂化为O(len(set_object))

>>> s1 - s2 
{'five'}
>>> s2 - s1
{'seven', 'six', 'zero'}    

也可以写成:

list

在这种情况下,您可能需要转换为list(s1 - s2),如果有必要,相应地转换为list(s2 - s1)list

或者,您可以使用source_list理解并制作diff_listin集,以便使用uniques运算符进行快速成员资格测试,从而做同样的事情:

对于source_unique = [v1 for v1 in source_list if v1 not in set(diff_list)] source_unique ['five'] 列表:

diff_unique

对于diff_unique = [v1 for v1 in diff_list if v1 not in set(source_list)] diff_unique ['zero', 'six', 'seven'] 列表:

O(len(list))

除非我误解了我的时间复杂性,否则又是<item name="windowActionBar">false</item>

答案 1 :(得分:1)

您可以使用套装:

source_list = ["one", "two", "three", "four", "five"]
diff_list = ["zero", "one", "two", "three", "four", "six", "seven"]


print("Unique elements in source_list: {0}".format(set(source_list)-set(diff_list)))
print("Unique elements in diff_list: {0}".format(set(diff_list)-set(source_list)))

打印出来:

Unique elements in source_list: set(['five'])
Unique elements in diff_list: set(['seven', 'six', 'zero'])

答案 2 :(得分:0)

您可以使用集来执行此操作

source_list = ["one", "two", "three", "four", "five"]
diff_list = ["zero", "one", "two", "three", "four", "six", "seven"]

source_unique = list(set(source_list) -  set(diff_list))
diff_unique =  list(set(diff_list) -  set(source_list))