简体   繁体   English

Python 列表和元组解包

[英]Python list and tuple Unpacking

thanks for answering me at the first.. I have a List or a Tuple in Python;感谢您首先回答我。我在 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 first ====> 它将返回1

but when I use it inside [ ] its like below:但是当我在 [ ] 中使用它时,如下所示:

list1[first] ====> it will return 2 list1[first] ====> 它将返回2

seams it wont count [0] index in this mod!!接缝它不会在这个 mod 中计算 [0] 索引!! why?为什么? and how to fix?以及如何解决?

first is set to 1, so normal to get the second element of the list. first设置为 1,所以正常获取列表的第二个元素。 If first was set to 'spam' for instance, list1[first] would just fail:例如,如果first设置为“垃圾邮件”,则list1[first]将失败:

>>> 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:我建议改用dict

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

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

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

list1[first-1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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