簡體   English   中英

Python:比較2個不同大小的元組列表

[英]Python: Compare 2 lists of tuples of different size

我有2個元組列表。 第一個列表包含帶有2元組的x個條目,而另一個列表包含帶有3個元組的y(更多)條目。

我想比較兩個列表,但只比較元組的第一個和第二個元素,基本上只是刪除dublicates,但在比較期間不應考慮第二個列表中每個元組的第三個條目。

list_x=[(1,1),(1,2),(2,3),(2,5),(4,6), ...]
list_y=[(1,1,33),(1,3,65),(2,4,11), ...]

現在我想創建一個新列表,其中list_y中也出現在list_x中的所有元素都將被刪除。 結果列表應如下所示:

[(1,3,65),(2,4,11), ...]

對於具有相同大小的元組列表,只需將列表轉換為集合並減去兩個列表即可:

newlist = list(set(list_y) - set(list_x))

也可以通過元組的第二個元素對結果列表進行排序:

newlist.sort(key=lambda tup: tup[1])

但現在問題是:如果列表如上所示,怎么可能這樣做呢?

你可以將list_x轉換為一個集合,然后遍歷list_y並檢查list_y的前兩個元素是否存在於集合中,如果不存在則將它們包含在結果列表中,這可以在列表list_y中完成如下。 示例 -

list_x=[(1,1),(1,2),(2,3),(2,5),(4,6), ...]
list_y=[(1,1,33),(1,3,65),(2,4,11), ...]

list_x_set = set(list_x)

result = [item for item in list_y if item[0:2] not in list_x_set]

演示 -

In [57]: list_x=[(1,1),(1,2),(2,3),(2,5),(4,6)]

In [58]: list_y=[(1,1,33),(1,3,65),(2,4,11)]

In [59]: list_x_set = set(list_x)

In [60]: result = [item for item in list_y if item[0:2] not in list_x_set]

In [62]: result
Out[62]: [(1, 3, 65), (2, 4, 11)]

請嘗試以下代碼:

set_x = set(list_x)
answer = sorted([t for t in list_y if (t[0], t[1]) not in set_x], key=lambda t:t[1])
with for loops 

list_x=[(1,1),(1,2),(2,3),(2,5),(4,6)]
list_y=[(1,1,33),(1,3,65),(2,4,11)]

for elx in list_x:
    for ely in list_y:
        if ely[:-1] == elx:
            list_y.remove(ely)


print(list_y)

[(1, 3, 65), (2, 4, 11)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM