簡體   English   中英

從 python 中的元組列表中過濾唯一對

[英]Filter unique pair from list of tuples in python

我有一個元組列表,例如 [(A,B),(B,A),(D,C),(E,F),(C,D),(F,E)]。 我想要結果為 [(A,B),(C,D),(E,F)]?

例子:

[('1.1.1.10', '140.205.94.193'), ('1.1.1.10', '157.240.16.35'), ('1.1.1.10', '172.217.163.110'),('157.240.16.35', '1.1.1.10'),('140.205.94.193', '1.1.1.10')]

預期結果:

[('1.1.1.10', '140.205.94.193'),('1.1.1.10', '157.240.25.35'),('1.1.1.10', '172.217.163.110'),]

這會生成一個列表,其中沒有x的重復排列

a = [('1.1.1.10', '140.205.94.193'),
     ('1.1.1.10', '157.240.16.35'),
     ('1.1.1.10', '172.217.163.110'),
     ('157.240.16.35', '1.1.1.10'),
     ('140.205.94.193', '1.1.1.10')]


def clean(x):
    heap = []
    for i in x:
        if (i[0], i[1]) not in heap and (i[1], i[0]) not in heap:
            heap.append(i)
    return heap
>>> clean(a)
[('1.1.1.10', '140.205.94.193'),
 ('1.1.1.10', '157.240.16.35'),
 ('1.1.1.10', '172.217.163.110')]

您可以利用 set() 和 sorted() 以任何順序消除重復的元組。

raw =[
    ('1.1.1.10', '140.205.94.193'), 
    ('1.1.1.10', '157.240.16.35'), 
    ('1.1.1.10', '172.217.163.110'),
    ('157.240.16.35', '1.1.1.10'),
    ('140.205.94.193', '1.1.1.10')
]

print(list(set([tuple(sorted(r)) for r in raw])))

結果:

[('1.1.1.10', '140.205.94.193'), ('1.1.1.10', '157.240.16.35'), ('1.1.1.10', '172.217.163.110')]

看起來你有一個元組數組? 我相信您可以創建另一個數組,使 arr2[1] = arr[1]。 arr[5] = arr2[2]。 arr[6] = arr2[3]。

那就是如果你總是有相同的尺寸列表,因為它非常小。 這可能是最短的方法

這是一些可以完成這項工作的巫術。

(這有點神秘,所以如果我是你,我會做一些更明確的事情,比如這里可用的選項: Remove duplicates with a different equality test in Python

data =  [('1.1.1.10', '140.205.94.193'), ('1.1.1.10', '157.240.16.35'), ('1.1.1.10', '172.217.163.110'),('157.240.16.35', '1.1.1.10'),('140.205.94.193', '1.1.1.10')]

res = [(a, b) for a, b in reversed(data) if data.pop() and (a, b) not in data and (b, a) not in data]

暫無
暫無

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

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