从该列表中:
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
循环
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]]
换句话说,当列表中的数字不符合顺序或者是一个混乱的列表时,它就不可用了
所以我有更好的答案来解决这个问题
使用^{} :
输出:
旁注:当您不需要使用全局变量时,请避免使用全局变量
可以将^{} 与list comprehension一起使用
这可以分配给变量
L
,如中所示相关问题 更多 >
编程相关推荐