Domanda

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']
È stato utile?

Soluzione

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 []

Altri suggerimenti

Use slicing:

>>> lis = ['a','b','c']
>>> a, b = lis[0], lis[1:]
>>> a
'a'
>>> b
['b', 'c']
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top