简体   繁体   English

在一行中解包函数返回值到单个值和元组

[英]Unpacking function return values to single value and tuple, in one line

I often use library functions which return many values in a tuple:我经常使用在元组中返回许多值的库函数:

def f():
    return "a", "b", "c", "d"

Is it possible to (in a single step) unpack the first value while keeping the rest in a tuple?是否可以(在一个步骤中)解压第一个值,同时将其余值保留在一个元组中? Ie do this:即这样做:

ret = f()
a, b_to_d = ret[0], ret[1:]

but in one line.但在一行。

Yes, using the * syntax below:是的,使用下面的*语法:

>>> def f():
...  return 1,2,3,4
...
>>> a,*b = f()
>>> a
1
>>> b
[2, 3, 4]
>>> a,*b,c = f()  # * can be used in other positions, too
>>> a,b,c
(1, [2, 3], 4)

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

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