Python版本为2.7版解压缩

问题描述 投票:34回答:3

正如here所提到的,你可以使用星号来解包未知数量的变量(比如在函数中),但仅限于python 3:

>>> a, *b = (1, 2, 3)
>>> b
[2, 3]
>>> a, *b = (1,)
>>> b
[]

在python 2.7中,我能想到的最好的是(并不可怕,但很烦人):

c = (1, 2, 3)
a, b = c[0], c[1:] if len(c) > 1 else []

有没有办法从__future__像分区导入它,或者我需要自己的函数在python 2.7中进行未知长度的解包?

python iterable-unpacking
3个回答
31
投票

在python 2.X中,你可以这样做:

c = (1, 2, 3)
a, b = c[0], c[1:]

只要c至少有一个成员它将起作用,因为如果c只有1件事,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

2
投票
(a,b) = (None, []) if not len(c) else (c[0], c[1:])

也是一个处理c是空序列的情况的选项,尽管它不能区分[None]和[]作为a,b的赋值。所以小心使用它,try / except可能是最好的。

在处理空容器时,我发现Python 3和2.7之间没有真正的区别,但是Python 3的优点在于它适用于任何可迭代的。

如果你知道c是一个生成器,这在2.7中工作。

a,b = c.next(), c

但解压缩的全部美感似乎需要Python 3。


0
投票

answer to ex13.py

from sys import argv

script=argv

def Fun(arg1, *argv): 
    print "First argument :", script 

    for arg in argv: 
        print"Your variable is:", arg

Fun('scrpit', 'first', 'second', 'third')
© www.soinside.com 2019 - 2024. All rights reserved.