英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论