Let's say I have a list of tuples and a simple function that takes two arguments:
a_list = [(1,6), (6,8)]
add_it(a + b)
I now want to unpack the tuple into the function. I know I can do it by indices:
l = [add_it(tup[0], tup[1]) for tup in a_list]
But I kinda expected this would work, too:
l = [add_it(a, b) for tup in a_list for a, b in tup]
Because this works:
tup = (3,5)
a, b = tup
>>> 3 5
Can someone point me to what I am missing?
You should do:
l = [add_it(a, b) for a, b in a_list]
# or
l = [add_it(*tup) for tup in a_list]
because
a, b in tup
cannot work as tup
does not contain pairs, a_list
does! Translated to your nested logic that would be:
l = [add_it(*(x for x in tup)) for tup in a_list]
But that is just unnecessarily wordy.
no need for a double loop. Just unpack in the loop arguments
l = [add_it(tup[0], tup[1]) for tup in a_list]
becomes
l = [add_it(a,b) for a,b in a_list]
note: that would work as well (unpacking arguments):
l = [add_it(*tup) for tup in a_list]
Because in your innermost for
statement you are iterating over the tuple, so you cannot unpack it. You unpack the individual items of a sequence. If it were a tuple of pairs or a list of pairs, then it would work.
>>> a_list = [(1,6), (6,8)]
>>> b_list = [[(1,6)], [(6,8)]]
>>> def add_it(a, b): return a+b
...
>>> l = [add_it(a, b) for tup in a_list for a, b in tup]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
TypeError: 'int' object is not iterable
>>> l = [add_it(a, b) for tup in b_list for a, b in tup]
>>> l
[7, 14]
And, as pointed out by others, it is overengineered, you only need one for
expression in your comprehension since a_list
is already a list of pairs:
>>> [add_it(a,b) for a,b in a_list]
[7, 14]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.