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

问题描述

有人提到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()]

解决方法

从此列表:

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

我正在尝试创建:

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

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

global n

n = [1,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