简体   繁体   English

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

[英]Compare two nested lists and keep the union of elements

The title may be misleading.标题可能具有误导性。 I will try to explain as clear as possible.我会尽量解释清楚。 I have two set of lists:我有两组列表:

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
    ]

I would like to compare first list of a with first list of b and so on.我想将afirst listb的第first list进行比较,依此类推。 Remove duplicates if I found any.如果我发现任何重复项,请删除。 The final outcome will look like this:最终结果将如下所示:

c = [
     [(1.5, 13), (1.5, 16), (1, 2), (1.5, 3)], #first list
     [(5.4, 100.5), (5.3, 100.5) ] #second list
    ]

As you can see, a and b will eventually append forming c .如您所见, ab最终将 append 形成c However, duplicates will not be appended as shown in second list of c .但是,不会附加重复项,如csecond list所示。 Position is not mutable. Position 不可变。

How can I achieve this efficiently?我怎样才能有效地实现这一目标?

Use zip to zip the two lists together, andset to remove duplicates from the concatenated pairs:一起使用zip到 zip 两个列表,并set从串联对中删除重复项:

[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)]]

If you want to maintain order(sets are unordered), use a dict and get the keys with dict.fromkeys (assuming Python 3.6+ for ordered dictionaries):如果要保持顺序(集合是无序的),请使用 dict 并使用dict.fromkeys获取键(假设 Python 3.6+ 用于有序字典):

[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)]]

For lower versions of python(dictionaries are unordered), you will need to use a collections.OrderedDict :对于较低版本的python(字典无序),您需要使用collections.OrderedDict

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)]]

If you want the tuples to be sorted by the first element, use sorted :如果您希望元组按第一个元素排序,请使用sorted

[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)]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM