Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map(function, sequence) where function returns two values

Tags:

python

Look at the following Python code:

def function(x):
    return x, x+1

sequence = range(5)

map(function, sequence)

this returns

[(0,1), (1,2), (2,3), (3,4), (4,5)]

I want to get the output

[0, 1, 2, 3, 4], [1, 2, 3, 4, 5]

That means, I want to get the two outputs of function into two different lists. Can I achieve this without looping over my lists?

In the real code I will not have lists of integers, but of class instances. So I might get some copy/deepcopy issues, which I would like to avoid.

like image 882
Till B Avatar asked Dec 12 '22 10:12

Till B


1 Answers

Hope this helps:

>>> a = [(0,1), (1,2), (2,3), (3,4), (4,5)]
>>> zip(*a)
[(0, 1, 2, 3, 4), (1, 2, 3, 4, 5)]

http://docs.python.org/library/functions.html#zip

like image 167
Savino Sguera Avatar answered Dec 28 '22 23:12

Savino Sguera