使用索引获取项目,Python [英] Using an index to get an item, Python

查看:156
本文介绍了使用索引获取项目,Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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。

Example: Say it was given 0, it would return A. Given 2, it would return C. Given 4, it would return E.

推荐答案

你展示的是什么,('A','B', 'C','D','E'),不是列表,它是元组(圆括号而不是方括号表示)。然而,无论是索引列表还是一个元组(用于在索引处获取一个项目),在任何一种情况下都将索引附加在方括号中。

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.

这篇关于使用索引获取项目,Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆