使用索引获取项目 [英] Using an index to get an item
问题描述
我在 python 中有一个列表 ('A','B','C','D','E'),如何获取特定索引号下的项目?
I have a list in python ('A','B','C','D','E'), how do I get which item is under a particular index number?
示例:
- 假设它被赋予 0,它会返回 A.
- 给定 2,它将返回 C.
- 给定 4,它将返回 E.
推荐答案
What you show, ('A','B','C','D','E')
,不是 list
,它是一个 tuple
(圆括号而不是方括号表明了这一点).然而,无论是索引列表还是元组(用于在索引处获取一个项目),在任何一种情况下,您都将索引附加在方括号中.
What you show, ('A','B','C','D','E')
, is not a list
, it's a tuple
(the round parentheses instead of square brackets show that). Nevertheless, whether it to index a list or a tuple (for getting one item at an index), in either case you append the index in square brackets.
所以:
thetuple = ('A','B','C','D','E')
print thetuple[0]
打印A
,等等.
元组(不同于列表)是不可变的,所以你不能赋值给thetuple[0]
等(你可以赋值到列表的索引).但是,在任何一种情况下,您都可以通过索引直接访问(获取")该项目.
Tuples (differently from lists) are immutable, so you couldn't assign to thetuple[0]
etc (as you could assign to an indexing of a list). However you can definitely just access ("get") the item by indexing in either case.
这篇关于使用索引获取项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!