Search code examples
pythonlistlambdagroup-byenumerate

Adding data to an array instead of print?


So I found a great answer to a prblem i was having here: Identify groups of continuous numbers in a list.

my code is now:

for k, g in groupby(enumerate(cycles), lambda (i,x):i-x):
    print map(itemgetter(1), g)

which gives

[1, 2, 3, 4, 5, 6, 7, 8]
[5]
[1, 2]

which is great.

However I want to be able to do stuff with this info. How do I write this to an array or something?


Solution

  • Just do it as follows:

    result = []
    for k, g in groupby(enumerate(cycles), lambda (i,x):i-x):
        result.append(map(itemgetter(1), g))
    
    print result
    

    Or just use list comprehension:

    result = [map(itemgetter(1), g) for k, g in groupby(enumerate(cycles), lambda (i,x):i-x)]