如何在列表中找到相同的值并将新列表分组?

2024-04-23 15:27:09 发布

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

从该列表中:

N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]

我试图创造:

L = [[1],[2,2],[3,3,3],[4,4,4,4],[5,5,5,5,5]]

任何发现相同的值都被分组到它自己的子列表中。 这是我到目前为止的尝试,我想我应该使用while循环

global n

n = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5] #Sorted list
l = [] #Empty list to append values to

def compare(val):
   """ This function receives index values
   from the n list (n[0] etc) """
   
   global valin
   valin = val

   global count
   count = 0

    for i in xrange(len(n)):
        if valin == n[count]: # If the input value i.e. n[x] == n[iteration]
            temp = valin, n[count]
             l.append(temp) #append the values to a new list
             count +=1
        else:
          count +=1
    

for x in xrange (len(n)):
    compare(n[x]) #pass the n[x] to compare function

Tags: thetoin列表forcountfunctionval
3条回答

有人提到N=[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 1]它将得到[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5], [1]]

换句话说,当列表中的数字不符合顺序或者是一个混乱的列表时,它就不可用了

所以我有更好的答案来解决这个问题

from collections import Counter

N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
C = Counter(N)

print [ [k,]*v for k,v in C.items()]

使用^{}

from itertools import groupby

N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]

print([list(j) for i, j in groupby(N)])

输出:

[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]

旁注:当您不需要使用全局变量时,请避免使用全局变量

可以将^{}list comprehension一起使用

>>> l =  [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
>>> [list(v) for k,v in itertools.groupby(l)]
[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]

这可以分配给变量L,如中所示

L = [list(v) for k,v in itertools.groupby(l)]

相关问题 更多 >