摆脱重复的自我价值,只保留 (2,0) (0,2) 中的一个?

问题描述 投票:0回答:1

根据@KellyBundy的回答,我想摆脱重复的自我价值(2, 2), (0, 0) 只保留 (2, 1) or (1, 2), keep only either (1, 0) or (0, 1) 并去掉 repeated (0, 2)

 [(0, 2), (2, 2), (2, 1), (1, 2), (2, 2), (0,2),  (2, 2), (2, 1), (1, 0), (0, 0), (0, 1)]

出于这个 从 itertools 成对导入,链

lis = [(0, [75, 1, 30]), (1, [41, 49, 55]), (2, [28, 53, 45])]

found = [*chain(*(pairwise(a) for *a, a[1:] in lis))]

print(found)
python tuples list-comprehension
1个回答
0
投票
mylist =  [(0, 2), (2, 2), (2, 1), (1, 2), (2, 2), (0,2),  (2, 2), (2, 1), (1, 0), (0, 0), (0, 1)]
seen = set()
final = [(i,j) for i,j in mylist if i!=j and (i+j, abs(i-j)) not in seen and not seen.add((i+j, abs(i-j)))]

我们过滤 ((i+j), abs(i-j))

如果你真的需要一个衬里,我们可以使用 lambda 函数

list(filter(lambda e, seen=set(): e[0]!=e[1] and (e[0]+e[1], abs(e[0]-e[1])) not in seen and not seen.add((e[0]+e[1], abs(e[0]-e[1]))), mylist))

i+j 和 abs(i-j) 这里是和和绝对差。它使逻辑更简单,因为 (x,y) 和 (y,x) 具有相同的绝对差和相同的总和。 (i+j, abs(i+j)) 是一个包含总和和绝对差的元组

在这里看到的是一个 python set,它可以用来有效地检查其中是否已经存在一些东西。

© www.soinside.com 2019 - 2024. All rights reserved.