英文:
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
和右侧的l
。 l 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]))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论