如何在列表中找到相同的值并将新列表组合在一起? [英] How can I find same values in a list and group together a new list?
本文介绍了如何在列表中找到相同的值并将新列表组合在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从此列表中:
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]]
Someone mentions for N=[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 1]
it will get [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5], [1]]
换句话说,当列表的数字不按顺序或列表混乱时,它不可用.
In other words, when numbers of the list isn't in order or it is a mess list, it's not available.
所以我有更好的答案来解决这个问题.
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屋!
查看全文