简体   繁体   中英

How do I unpack a list with fewer variables?

k = [u'query_urls', u'"kick"', u'"00"', u'msg=1212', u'id=11']

>>> name, view, id, tokens = k
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

I need to provide 5 variables to unpack this list. Is there a way to unpack with fewer, so that tokens gets the rest of the list. I don't want to write another line to append to a list....

Thanks.


Of course I can slice a list, assign individually, etc. But I want to know how to do what I want using the syntax above.

In Python 3 you can do this: (edit: this is called extended iterable unpacking )

name, view, id, *tokens = k

In Python 2, you will have to do this:

(name, view, id), tokens = k[:3], k[3:]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM