首页 > 文章列表 > Python如何用下标取得列表的单个值

Python如何用下标取得列表的单个值

python列表
348 2022-08-07

下标说明

1、使用的下标超出了列表中值的个数,Python 将给出 IndexError 出错信息。

2、下标只能是整数,不能是浮点值。

3、列表也可以包含其他列表值。

实例

list1 = [1,2,43]
print(list1)
 
print(list1[0])
 
1.如果使用的下标超出了列表中值的个数,Python 将给出 IndexError 出错信息。
print(list1[5])
IndexError: list index out of range
 
2.下标只能是整数,不能是浮点值。下面的例子将导致 TypeError 错误:
print(list1[5.0])
TypeError: list indices must be integers or slices, not float
 
3.列表也可以包含其他列表值。这些列表的列表中的值,可以通过多重下标来访
问,像这样:
list = [[1, 2, 3], [4, 5, 6]]
print(list[0][1])
打印结果:
2

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。