如何在以下元组列表中查找重复值?在Python中的元组列表中查找重复值
[(1622, 4081), (1622, 4082), (1624, 4083), (1626, 4085), (1650, 4086), (1650, 4090)]
我希望得到一个列表,如:
[4081, 4082, 4086, 4090]
我一直在使用itemgetter
然后按选项尝试,但没有奏效。
如何做到这一点?
如何在以下元组列表中查找重复值?在Python中的元组列表中查找重复值
[(1622, 4081), (1622, 4082), (1624, 4083), (1626, 4085), (1650, 4086), (1650, 4090)]
我希望得到一个列表,如:
[4081, 4082, 4086, 4090]
我一直在使用itemgetter
然后按选项尝试,但没有奏效。
如何做到这一点?
使用一个有序字典,第一项为键和值的第二项列表(其中创建副本使用dict.setdefalt()
)然后拿起那些有长度超过1:
>>> from itertools import chain
>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> for i, j in lst:
... d.setdefault(i,[]).append(j)
...
>>>
>>> list(chain.from_iterable([j for i, j in d.items() if len(j)>1]))
[4081, 4082, 4086, 4090]
+5谢谢!它的工作完美!没有足够的意见来赞扬你! –
没有测试过这一点....(编辑:是的,它的工作原理)
l = [(1622, 4081), (1622, 4082), (1624, 4083), (1626, 4085), (1650, 4086), (1650, 4090)]
dup = []
for i, t1 in enumerate(l):
for t2 in l[i+1:]:
if t1[0]==t2[0]:
dup.extend([t1[1], t2[1]])
print dup
作为替代方案,如果你想使用groupby
,这里是一个办法做到这一点:
In [1]: from itertools import groupby
In [2]: ts = [(1622, 4081), (1622, 4082), (1624, 4083), (1626, 4085), (1650, 4086), (1650, 4090)]
In [3]: dups = []
In [4]: for _, g in groupby(ts, lambda x: x[0]):
...: grouped = list(g)
...: if len(grouped) > 1:
...: dups.extend([dup[1] for dup in grouped])
...:
In [5]: print(dups)
[4081, 4082, 4086, 4090]
您可以使用groupby
从元组的第一个元素进行分组,并将重复值从元组添加到列表中。
另一种方法(没有任何进口):
In [896]: lot = [(1622, 4081), (1622, 4082), (1624, 4083), (1626, 4085), (1650, 4086), (1650, 4090)]
In [897]: d = dict()
In [898]: for key, value in lot:
...: d[key] = d.get(key, []) + [value]
...:
...:
In [899]: d
Out[899]: {1622: [4081, 4082], 1624: [4083], 1626: [4085], 1650: [4086, 4090]}
In [900]: [d[key] for key in d if len(d[key]) > 1]
Out[900]: [[4086, 4090], [4081, 4082]]
In [901]: sorted([num for num in lst for lst in [d[key] for key in d if len(d[key]) > 1]])
Out[901]: [4081, 4081, 4082, 4082]
可您发布的尝试? – 0xtvarun
转到下面的链接可能是它可以帮助你。 [link1](http://stackoverflow.com/questions/32464290/python-find-tuples-from-a-list-of-tuples-having-duplicate-data-in-the-0th-elem)[link2]( http://stackoverflow.com/questions/17482944/find-duplicate-items-within-a-list-of-list-of-tuples-python) –