编程语言
首页 > 编程语言> > 如何找到重复值并合并它们? – Python

如何找到重复值并合并它们? – Python

作者:互联网

所以基本上你有一个列表如下:

l = ['a','b','a','b','c','c']

输出应该是:

[['a','a'],['b','b'],['c','c']]

所以基本上将重复的值放在一个列表中,

我试过了:

l = ['a','b','a','b','c','c']
it=iter(sorted(l))
next(it)
new_l=[]
for i in sorted(l):
   new_l.append([])
   if next(it,None)==i:
      new_l[-1].append(i)
   else:
      new_l.append([])

但是不起作用,如果它确实有效,它就不会有效率

解决方法:

对列表排序然后使用itertools.groupby:

>>> from itertools import groupby
>>> l = ['a','b','a','b','c','c']
>>> [list(g) for _, g in groupby(sorted(l))]
[['a', 'a'], ['b', 'b'], ['c', 'c']]

编辑:这可能不是最快的方法,排序是平均情况的O(n log n)时间复杂度,并非所有解决方案都需要(参见注释)

标签:python,merge,duplicates,list,nested-lists
来源: https://codeday.me/bug/20190716/1473860.html