新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

python怎么根据索引获取元素,python查找某个元素的索引

发布时间:2023-10-12 06:23:10

python怎样根据索引获得元素

在 Python 中,可使用索引来获得列表、元组和字符串中的元素。索引从0开始,表示第一个元素,顺次递增。
对列表和元组,可使用方括号 [] 加上索引来获得元素。例如:

my_list = ['apple', 'banana', 'cherry']
print(my_list[0])  # 输出: 'apple'
print(my_list[2])  # 输出: 'cherry'
my_tuple = ('apple', 'banana', 'cherry')
print(my_tuple[0])  # 输出: 'apple'
print(my_tuple[2])  # 输出: 'cherry'

对字符串,也能够使用方括号 [] 加上索引来获得字符。例如:

my_string = 'hello world'
print(my_string[0])  # 输出: 'h'
print(my_string[6])  # 输出: 'w'

如果索引超越了列表、元组或字符串的范围,会抛出 IndexError 异常。