元组比较的列表理解

2024-04-23 14:47:13 发布

您现在位置:Python中文网/ 问答频道 /正文

输入:[("abc", 1, "def"), ("abc", 1, "ghi"), ("bc", 2, "a"), ("bc", 2, "b"), ("bc", 3, "a")]

预期输出:[("abc", 1, "def"), ("bc", 2, "a"), ("bc", 3, "a")]

我在试什么比如:- field_list = [field for i, field in enumerate(field_list) for cmp_field in field_list[i+1:] if]..不知道if怎么适合这里?你知道吗

我想通过列表理解来实现这一点。获取输出的逻辑—删除重复项(如果项[0]和项[1]相同,则元组被视为重复项)。你知道吗

我可以实现它使用传统的for循环,但我想得到这个列表的理解。有什么想法吗?你知道吗

编辑:(“abc”,1,“def”)和(“abc”,1,“ghi”)是重复的,所以我可以选择第一个。你知道吗


Tags: infield列表forifdef传统逻辑
3条回答
output = [(x, y, z) for j, (x, y, z) in enumerate(input) if (x, y) not in [(x2, y2) for x2, y2, _ in input[:j]]]
# output = [('abc', 1, 'def'), ('bc', 2, 'a'), ('bc', 3, 'a')]

但是,使用传统的for循环可能更有效,因为您不需要在每次迭代时构建第二个列表(或者Ashwini Chaudhary建议的一个集合)。你知道吗

我使用了groupby,这是一个中间步骤。 . 你知道吗

In [40]: l=[("abc", 1, "def"), ("abc", 1, "ghi"), ("bc", 2, "a"), ("bc", 2, "b"), ("bc", 3, "a")]

In [41]: from itertools import groupby

In [42]: groups=[list(g) for k,g in groupby(l,key=itemgetter(1))]

In [43]: groups
Out[43]: 
[[('abc', 1, 'def'), ('abc', 1, 'ghi')],
 [('bc', 2, 'a'), ('bc', 2, 'b')],
 [('bc', 3, 'a')]]

In [44]: [elem[0] for elem in groups]
Out[44]: [('abc', 1, 'def'), ('bc', 2, 'a'), ('bc', 3, 'a')]

this中获得灵感,你可以试试

inp = [("abc", 1, "def"), ("abc", 1, "ghi"), ("bc", 2, "a"), ("bc", 2, "b"), ("bc", 3, "a")]
res = []
[res.append(el) for el in inp if not [tmp for tmp in res if tmp[0] == el[0] and tmp[1] == el[1]]]

尽管我相信常规的for循环会更适合你的情况。你知道吗

相关问题 更多 >