简体   繁体   English

通过列表理解将元组分解为函数

[英]Tuple unpacking into function with list comprehension

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! a, b in tup不能工作,因为tup不包含对,而a_list可以! 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. 但这只是不必要的罗word。

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. 因为在最里面的for语句中,您正在对元组进行迭代 ,所以您无法解压缩它。 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: 而且,正如其他人所指出的,它是过度设计的,你只需要一个for表达你的理解,因为a_list已经是对的列表:

>>> [add_it(a,b) for a,b in a_list]
[7, 14]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM