Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 比较两个嵌套列表并保持元素的并集_Python_List - Fatal编程技术网

Python 比较两个嵌套列表并保持元素的并集

Python 比较两个嵌套列表并保持元素的并集,python,list,Python,List,标题可能具有误导性。我会尽量解释清楚。 我有两套清单: a = [ [(1.5, 13), (1.5, 16)], #first list [(5.4, 100.5), (5.3, 100.5)] #second list ] b = [ [(1, 2), (1.5, 3)], #first list [(5.4, 100.5), (5.3, 100.5)] #second list ] 我想比较a的first list和b的fir

标题可能具有误导性。我会尽量解释清楚。 我有两套清单:

a = [
      [(1.5, 13), (1.5, 16)], #first list
      [(5.4, 100.5), (5.3, 100.5)] #second list
    ]

b = [
     [(1, 2), (1.5, 3)], #first list
     [(5.4, 100.5), (5.3, 100.5)] #second list
    ]
我想比较
a的
first list
b的
first list
等等。如果发现任何重复项,请删除。最终结果如下所示:

c = [
     [(1.5, 13), (1.5, 16), (1, 2), (1.5, 3)], #first list
     [(5.4, 100.5), (5.3, 100.5) ] #second list
    ]
如您所见,
a
b
最终将追加
c
。但是,不会如
c
second list
所示追加重复项。位置是不可变的

如何有效地实现这一点?

用于将两个列表压缩在一起,并从串联对中删除重复项:

[list(set(x + y)) for x, y in zip(a, b)]
# [[(1.5, 16), (1, 2), (1.5, 13), (1.5, 3)], [(5.4, 100.5), (5.3, 100.5)]]
如果要保持顺序(集合是无序的),请使用dict并使用获取键(假定Python 3.6+用于有序字典):

对于较低版本的python(字典是无序的),您需要使用:

如果希望元组按第一个元素排序,请使用:

[list(dict.fromkeys(x + y)) for x, y in zip(a, b)]
# [[(1.5, 13), (1.5, 16), (1, 2), (1.5, 3)], [(5.4, 100.5), (5.3, 100.5)]]
from collections import OrderedDict

[list(OrderedDict.fromkeys(x + y)) for x, y in zip(a, b)]
# [[(1.5, 13), (1.5, 16), (1, 2), (1.5, 3)], [(5.4, 100.5), (5.3, 100.5)]]
[sorted(set(x + y)) for x, y in zip(a, b)]
# [[(1, 2), (1.5, 3), (1.5, 13), (1.5, 16)], [(5.3, 100.5), (5.4, 100.5)]]