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

2023-12-06

从这个列表:

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 loop?

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

Use itertools.groupby:

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)])

Output:

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

旁注:在不使用全局变量时防止使用全局变量need to.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在列表中找到相同的值并将其分组到一个新列表中? 的相关文章

随机推荐