简体   繁体   中英

Python list and tuple Unpacking

thanks for answering me at the first.. I have a List or a Tuple in Python; try to unpack instead of index like below:

list1 = [1,2,3,4]
first,second,third,fourth = list1

now its ok if I use it like this:

first ====> it will return 1

but when I use it inside [ ] its like below:

list1[first] ====> it will return 2

seams it wont count [0] index in this mod!! why? and how to fix?

first is set to 1, so normal to get the second element of the list. If first was set to 'spam' for instance, list1[first] would just fail:

>>> list1 = ["spam", "egg"]
>>> first, second = list1
>>> list1[first]

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not str

I suggest using a dict instead:

 >>> dict1 = {"first": 1, "second": 2}
 >>> dict1["first"]
 1

因为first持有整数1,所以list1[first]实际上就是list1[1]

如果您希望将list1的值用作基于 1 的索引但不想更改list1 ,则可以使用(例如):

list1[first-1]

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