去掉重复的自身数值,只保留其中一个 (2,0) (0,2)。

huangapple go评论55阅读模式
英文:

get rid of repeated self values and keep only one out of (2,0) (0,2)?

问题

根据 @KellyBundy 的答案,我想要消除重复的自值 (2, 2), (0, 0) 并保留 (2, 1) 或 (1, 2) 中的一个,只保留 (1, 0) 或 (0, 1) 并消除重复的 (0, 2)

以下是原始的列表:

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

这是从中提取所需值后的列表:

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

请注意,这是根据您的要求从原始列表中筛选出的值。

英文:

according to @KellyBundy answer, I'd like to get rid of repeated self-values (2, 2), (0, 0)
and keep only either (2, 1) or (1, 2), keep only either (1, 0) or (0, 1) and get rid of 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)]

out of this
from itertools import pairwise, chain

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)

答案1

得分: 1

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)))]

# We filter on ((i+j), abs(i-j))

if you really need a one-liner, we can use a lambda function

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 and abs(i-j) here are the sum and absolute difference. It makes the logic simpler since (x,y) and (y,x) have the same absolute difference and the same sum.
(i+j, abs(i+j)) is a tuple containing both the sum and absolute difference

seen here is a Python set, which can be used to efficiently check if something already exists within it.
英文:
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)))]

we filter on ((i+j), abs(i-j))

if you really need a one liner, we can use a lambda function

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 and abs(i-j) here are the sum and absolute difference. It makes the logic simpler since (x,y) and (y,x) have the same absolute difference and the same sum.
(i+j, abs(i+j)) is a tuple containing both the sum and absolute difference

seen here is a python set, which can be used to efficiently check if something already exists within it.

huangapple
  • 本文由 发表于 2023年2月18日 19:23:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492991.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定