使用三元运算符解压列表

huangapple go评论63阅读模式
英文:

Unpack a list with ternary operator

问题

以下是翻译好的部分:

I stumbled upon a weird behaviour when I want to unpack a list only if condition is true.
我在尝试仅在条件为真时解包列表时遇到了奇怪的行为。

How can I use the unpacking () based on a condition?
如何根据条件使用解包 (
)?

Example:
示例:

def foo1(x1, x2):
    print(x1, x2)

def foo2(x):
    print(x)

l = [7,8]
foo1(*l if True else l) # this works
foo2(*l if False else l) # this does not work
foo1(l if not True else *l) # this does not work
英文:

I stumbled upon a weird behaviour when I want to unpack a list only if condition is true.

How can I use the unpacking (*) based on a condition?

Example:

def foo1(x1, x2):
    print(x1, x2)

def foo2(x):
    print(x)

l = [7,8]
foo1(*l if True else l) # this works
foo2(*l if False else l) # this does not work
foo1(l if not True else *l) # this does not work

答案1

得分: 5

这不是解析为在左侧选择*l和右侧的ll if True else l 被评估,然后结果被无条件地解包。

没有办法有一个函数调用表达式有条件地解包或不解包参数。如果你在那里放一个*,就会有东西被解包。你可以做的是将l包装在另一个列表中,然后解包:

foo(*(l if condition else [l]))
英文:

That's not parsed as choosing between *l on the left and l on the right. l if True else l is evaluated, and then the result is unpacked, unconditionally.

There's no way to have a function call expression conditionally either unpack or not unpack an argument. Something's getting unpacked if you put a * there. What you can do is wrap l in another list and unpack that:

foo(*(l if condition else [l]))

huangapple
  • 本文由 发表于 2023年2月14日 21:32:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75448574.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定