I wrote a function which returns different outputs and I need to iteratively call the function for each element of an array (passed as an iterable).
However, I am only able to retrieve the output as a tuple and I can't figure out how to unpack each element. Here is a toy example:
def returninput(a,b,c):
return a,b,c
The following work but returns a list of tuples:
it=iter(np.linspace(1,100,100))
a=[returninput(elem, elem+1,elem+2) for elem in it]
In: a
Out: [(1.0, 2.0, 3.0),
(2.0, 3.0, 4.0),
(3.0, 4.0, 5.0),
(4.0, 5.0, 6.0),
.............
(99.0, 100.0, 101.0),
(100.0, 101.0, 102.0)]
I'd like to have a list of elements for each variable in output, so I tried:
it=iter(np.linspace(1,100,100))
a,b,c=[returninput(elem, elem+1,elem+2) for elem in it]
But I get too many values to unpack (expected 3)
.
Desired output would be:
In: a
Out: [1.0, 2.0, 3.0, 4.0,...,100]
In: b
Out: [2.0, 3.0, 4.0, 5.0,...,101]
In: c
Out: [3.0, 4.0, 5.0, 6.0,...,102]
Use zip
, you don't need the intermediate function:
a, b, c = list(zip(*[(elem, elem+1,elem+2) for elem in it]))
If you want a, b and c to be lists instead of tuples:
a, b, c = [list(x) for x in zip(*[(elem, elem+1,elem+2) for elem in it])]
Example:
>>> a, b, c = list(zip(*[(elem, elem+1,elem+2) for elem in range(100)]))
>>> a
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99)
>>> b
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100)
>>> c
(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101)
In your specific case you will have:
a,b,c=[list(x) for x in zip(*[returninput(elem, elem+1,elem+2) for elem in it])]