我有一個元組串列,例如 [(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'),]
uj5u.com熱心網友回復:
這將創建一個串列,其中沒有重復的排列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')]
uj5u.com熱心網友回復:
您可以利用 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')]
uj5u.com熱心網友回復:
看起來你有一個元組陣列?我相信您可以創建另一個陣列,例如 arr2[1] = arr[1]。arr[5] = arr2[2]。arr[6] = arr2[3]。
也就是說,如果您總是有相同大小的串列,因為它非常小。這可能是最短的方法
uj5u.com熱心網友回復:
這是一些可以完成這項作業的巫術。
(這有點神秘,所以如果我是你,我會做一些更明確的事情,比如這里提供的選項:在 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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/461232.html
標籤:Python python-2.7 独特
