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
groupby method. The groupby method will return a list of the tuples with the element and its group. In every iteration, convert the group of similar elements into a list. Append the list to the empty list.
Using Count() The python list method count() returns count of how many times an element occurs in list. So if we have the same element repeated in the list then the length of the list using len() will be same as the number of times the element is present in the list using the count(). The below program uses this logic.
Use itertools.groupby
:
from itertools import groupby N = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,5] print([list(j) for i, j in groupby(N)])
Output:
[[1], [2, 2], [3, 3, 3], [4, 4, 4, 4], [5, 5, 5, 5, 5]]
Side note: Prevent from using global variable when you don't need to.
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()]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With