蟒蛇 - 查找列表以及组合在一起的新列表相同的价值观 [英] Python - 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]
被发现是相同的任何值被分组到它自己的子列表。
这里是我的尝试,到目前为止,我想我应该使用,而
循环?
全球氮N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5] #Sorted名单
L = [] #Empty名单追加值DEF比较(VAL):
这个函数接收索引值
从n列表(N [0]等), 全球华菱
华菱= VAL 全球数
数= 0 对于我的xrange(LEN(N)):
如果华菱== N [统计]:#如果输入值即n [X] == N [迭代]
TEMP =华菱,N [计数]
l.append(TEMP)#append的值,以一个新的列表
数+ = 1
其他:
数+ = 1
在的xrange X(LEN(n))的:
比较(N [X])#pass的N [X]比较功能
有人提到了 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]
在换句话说,当该列表的号码是不是为了或者它一团糟列表,这是不可用的。
所以我有更好的回答来解决这个问题。
从收藏导入柜台N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
C =计数器(N)打印[K,] * V为K,V在C.items()]
I'm stuck figuring this out and wonder if anyone could point me in the right direction...
From this list:
N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5]
I'm trying to create:
L = [[1],[2,2],[3,3,3],[4,4,4,4],[5,5,5,5,5]]
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
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屋!