如何确定列表之间的差异?

时间:2017-05-02 05:09:45

标签: python algorithm python-2.7 python-3.x

我有两个清单:

first_list = [('A', 'Name A'), ('B', 'Name B'), ('C', 'Other Name')]
second_list = [('A', 'Name A'), ('B', 'Name B'), ('C', 'Name C'), ('D', 'Name D')]

我想要这样的清单:third_list = [('D', 'Name D')]

我使用过:third_list = list(set(second_list) ^ set(first_list))但它返回了我:third_list = [('C', 'Name C'), ('D', 'Name D')]

因此,您可以看到我想要列表,其中元组的第一项是不同的。 ('C', 'Other Name')('C', 'Name C')必须相同,因为元组中的第一项是相同的。

3 个答案:

答案 0 :(得分:1)

Check online demo

first_list = [('A', 'Name A'), ('B', 'Name B'), ('C', 'Other Name')]
second_list = [('A', 'Name A'), ('B', 'Name B'), ('C', 'Name C'), ('D', 'Name D')]

first_dict = dict(first_list)
second_dict = dict(second_list)
value = { k : second_dict[k] for k in set(second_dict) - set(first_dict) }
print(value)

答案 1 :(得分:1)

这将完成这项工作:

first_second = [('A', 'Name A'), ('B', 'Name B'), ('C', 'Other Name')]
second_second = [('A', 'Name A'), ('B', 'Name B'), ('C', 'Name C'), ('D', 'Name D')]
d_one=dict(first_second)
d_two=dict(second_second)
res=[(i,j) for i,j in d_two.items() if i in set(d_two).symmetric_difference(set(d_one)) ]

然后res

[('D', 'Name D')]

答案 2 :(得分:1)

[x for x in second_list if x[0] not in dict(first_list)]

[('D', 'Name D')]