I would like to unpack the return of a function into :

  1. a first variable always set up by the first returned value

  2. a second variable to store any exceeded returned value

To do so, I have this code working under python3.x. How could I make it works with python 2.x (python2.6 at least) ?

a,*b = ['a','b','c']

Edit: This would also work with :

a,*b = ['a']
有帮助吗?

解决方案

There is no straight forward way to do this in Python 2.7, instead you can create a new list without the first element and first element alone and unpack them into respective variables.

data = ['a','b','c']
a, b = data[0], data[1:]
print a, b

Output

a ['b', 'c']

This solution will still work, even if the RHS has only one element

data = ['a']
a, b = data[0], data[1:]
print a, b

Output

a []

其他提示

Use slicing:

>>> lis = ['a','b','c']
>>> a, b = lis[0], lis[1:]
>>> a
'a'
>>> b
['b', 'c']
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top