问题
Is there a clean/simple way to unpack a Python tuple on the right hand side from left to right?
For example for
j = 1,2,3,4,5,6,7
(1,2,3,4,5,6,7)
v,b,n = j[4:7]
Can I modify the slice notation so that v = j[6], b=j[5], n=j[4]
?
I realise I can just order the left side to get the desired element but there might be instances where I would just want to unpack the tuple from left to right I think.
回答1:
In case you want to keep the original indices (i.e. don't want to bother with changing 4 and 7 to 6 and 3) you can also use:
v, b, n = (j[4:7][::-1])
回答2:
This should do:
v,b,n = j[6:3:-1]
A step value of -1
starting at 6
回答3:
n,b,v=j[4:7]
will also work. You can just change the order or the returned unpacked values
回答4:
You could ignore the first after reversing and use extended iterable unpacking:
j = 1, 2, 3, 4, 5, 6, 7
_, v, b, n, *_ = reversed(j)
print(v, b, n)
Which would give you:
6 5 4
Or if you want to get arbitrary elements you could use operator.itemgetter
:
j = 1, 2, 3, 4, 5, 6, 7
from operator import itemgetter
def unpack(it, *args):
return itemgetter(*args)(it)
v,b,n = unpack(j, -2,-3,-4)
print(v, b, n)
The advantage of itemgetter is it will work on any iterable and the elements don't have to be consecutive.
回答5:
you can try this,
-1 mean looking from reverse, with last 3rd element to last element
>>> v,b,n=j[-1:-4:-1]
>>> print 'v=',v,'b=',b,'n=',n
v= 7 b= 6 n= 5
>>>
来源:https://stackoverflow.com/questions/38276068/unpack-a-python-tuple-from-left-to-right