Python star unpacking for version 2.7

自古美人都是妖i 提交于 2019-11-27 22:40:40
Andbdrew

in python 2.X, you can do:

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

as long as c has at least one member it will work because if c only has 1 thing in it c[1:] is [].

You should probably make sure there is at least one thing in c though, or else c[0] will raise an exception.

You could do something like:

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
Pete Cacioppi
(a,b) = (None, []) if not len(c) else (c[0], c[1:])

is also an option for handling the case where c is an empty sequence, although it won't distinguish between [None] and [] in terms as assignments to a, b. So use it with care, the try / except is probably best.

I can see no real difference between Python 3 and 2.7 when handling an empty container, but the nice thing about Python 3 here is it works with any iterable.

This works in 2.7 if you know c is a generator.

a,b = c.next(), c

But the full beauty of unpacking seems to require Python 3.

Haminger 2012

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')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!