簡體   English   中英

比較兩個嵌套列表並保持元素的並集

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

標題可能具有誤導性。 我會盡量解釋清楚。 我有兩組列表:

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
    ]

我想將afirst listb的第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
    ]

如您所見, ab最終將 append 形成c 但是,不會附加重復項,如csecond list所示。 Position 不可變。

我怎樣才能有效地實現這一目標?

一起使用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)]]

如果要保持順序(集合是無序的),請使用 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)]]

對於較低版本的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)]]

如果您希望元組按第一個元素排序,請使用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