[英]How to return an unpacked list in Python?
I'm trying to do something like this in python: 我想在python中做这样的事情:
def f():
b = ['c', 8]
return 1, 2, b*, 3
Where I want f
to return the tuple (1, 2, 'c', 8, 3)
. 我希望
f
返回元组(1, 2, 'c', 8, 3)
。 I found a way to do this using itertools
followed by tuple
, but this is not very nice, and I was wondering whether there exists an elegant way to do this. 我找到了一种方法,使用
itertools
后跟tuple
,但这不是很好,我想知道是否有一种优雅的方式来做到这一点。
The unpacking operator *
appears before the b
, not after it. 拆包操作员
*
出现在b
之前,而不是之后。
return (1, 2, *b, 3)
# ^ ^^ ^
However, this will only work on Python 3.5+ ( PEP 448 ), and also you need to add parenthesis to prevent SyntaxError. 但是,这只适用于Python 3.5+( PEP 448 ),还需要添加括号以防止出现SyntaxError。 In the older versions, use
+
to concatenate the tuples: 在旧版本中,使用
+
来连接元组:
return (1, 2) + tuple(b) + (3,)
You don't need the tuple
call if b
is already a tuple instead of a list: 如果
b
已经是元组而不是列表,则不需要tuple
调用:
def f():
b = ('c', 8)
return (1, 2) + b + (3,)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.