Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中的元组列表中查找重复值_Python_List_Tuples - Fatal编程技术网

在Python中的元组列表中查找重复值

在Python中的元组列表中查找重复值,python,list,tuples,Python,List,Tuples,如何在下面的元组列表中找到重复值 [(1622, 4081), (1622, 4082), (1624, 4083), (1626, 4085), (1650, 4086), (1650, 4090)] 我想得到如下列表: [4081, 4082, 4086, 4090] 我曾尝试使用itemgetter然后使用groupby选项,但没有成功 一个人怎么能做到这一点呢?还没有测试过这一点。。。。(编辑:是的,它起作用了) 我还没有测试过这个。。。。(编辑:是的,它起作用了) 使用有序字典,第

如何在下面的元组列表中找到重复值

[(1622, 4081), (1622, 4082), (1624, 4083), (1626, 4085), (1650, 4086), (1650, 4090)]
我想得到如下列表:

[4081, 4082, 4086, 4090]
我曾尝试使用
itemgetter
然后使用groupby选项,但没有成功

一个人怎么能做到这一点呢?

还没有测试过这一点。。。。(编辑:是的,它起作用了)

我还没有测试过这个。。。。(编辑:是的,它起作用了)


使用有序字典,第一个项目作为键,第二个项目列表作为值(对于使用
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]

使用有序字典,第一个项目作为键,第二个项目列表作为值(对于使用
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]

或者,如果您想使用
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
从元组的第一个元素进行分组,并将重复值添加到元组的列表中。

作为替代方法,如果您想使用
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
从元组的第一个元素进行分组,并将重复值添加到元组的列表中。

还有另一种方法(无任何导入):

另一种方法(无任何进口):


你能发布你的尝试吗?点击下面的链接可能会对你有所帮助。你能发布你的尝试吗?点击下面的链接可能会对你有所帮助+谢谢你!它的工作完美!没有足够的分数投票给你+谢谢你!它的工作完美!没有足够的分数投票给你!