bea*_*rdc 34 python iterable-unpacking
正如这里提到的,你可以使用star解压缩未知数量的变量(比如在函数中),但只能在python 3中:
>>> a, *b = (1, 2, 3)
>>> b
[2, 3]
>>> a, *b = (1,)
>>> b
[]
Run Code Online (Sandbox Code Playgroud)
在python 2.7中,我能想到的最好的是(并不可怕,但很烦人):
c = (1, 2, 3)
a, b = c[0], c[1:] if len(c) > 1 else []
Run Code Online (Sandbox Code Playgroud)
有没有办法从__future__像分区导入它,或者我需要自己的函数在python 2.7中进行未知长度的解包?
And*_*rew 31
在python 2.X中,你可以这样做:
c = (1, 2, 3)
a, b = c[0], c[1:]
Run Code Online (Sandbox Code Playgroud)
只要c至少有一个成员就可以工作,因为如果c只有一件事c[1:]就是[].
你可能应该确保至少有一件事c,否则c[0]会引发异常.
你可以这样做:
try:
c = tuple(c)
a, b = c[0], c[1:]
except TypeError, IndexError:
# c is not iterable, or c is iterable, but it doesn't have any stuff in it.
# do something else
pass
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19354 次 |
| 最近记录: |