从这个列表:
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