7

Is it possible to assign to a list slice in one go, that would achieve the following as:

mylist = [1,2,3,4,5,6,7]

xs = mylist[:-1]
x  = mylist[-1]

xs == [1,2,3,4,5,6]
x  == 7

I know I can write it like this:

xs,x = mylist[:-1], mylist[-1]

but I was wondering if it is possible to this any other way. Or have been spoilt by Haskell's pattern matching.

something like x,xs = mylist[:funky:slice:method:]

4

1 回答 1

11

你可以在 Python 3 中:

>>> *xs, x = [1, 2, 3, 4, 5, 6, 7]
>>> xs
[1, 2, 3, 4, 5, 6]
>>> x
7
于 2012-06-16T14:05:47.777 回答