如何在列表中找到相同的值并将新列表分组在一起? [英] How can I find same values in a list and group together a new list?

查看:193
本文介绍了如何在列表中找到相同的值并将新列表分组在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从此列表中:

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 循环吗?

Any value which is found to be the same is grouped into it's own sublist. Here is my attempt so far, I'm thinking I should use a 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


推荐答案

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

换句话说,当数字

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

So I have better answer to solve this problem.

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

这篇关于如何在列表中找到相同的值并将新列表分组在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆