访问列表元素

Python 中,如果想输出列表的内容,可以直接使用 Print() 函数。

通过索引访问单个元素

列表的索引从 0 开始,可以使用正向索引(从左到右)或负向索引(从右到左)访问元素。

fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry']

# 正向索引访问
print(fruits[0])    # 输出: apple
print(fruits[2])    # 输出: cherry

# 负向索引访问
print(fruits[-1])   # 输出: elderberry
print(fruits[-3])   # 输出: cherry

切片操作访问多个元素

使用切片操作可以获取列表的子列表。

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# 获取前三个元素
print(numbers[0:3])  # 输出: [0, 1, 2]

# 从索引2开始到末尾
print(numbers[2:])   # 输出: [2, 3, 4, 5, 6, 7, 8, 9]

# 获取偶数位置元素
print(numbers[::2])  # 输出: [0, 2, 4, 6, 8]

# 反向获取列表
print(numbers[::-1]) # 输出: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

遍历列表元素

可以使用 for 循环或 enumerate() 函数遍历列表。

for 循环

enumerate 函数

嵌套列表的元素访问

对于嵌套列表,需要使用多级索引访问内层元素。

最后更新于