在Python中,可以使用enumerate()
函数来遍历动态列表,并且可以获取到当前元素的索引。
下面是一个示例代码:
my_list = [1, 2, 3, 4, 5]
for index, value in enumerate(my_list):
print("当前索引:", index)
print("当前元素:", value)
print("")
# 在循环中修改列表
my_list[index] = value * 2
print("修改后的列表:", my_list)
运行上述代码,会输出以下结果:
当前索引: 0
当前元素: 1
当前索引: 1
当前元素: 2
当前索引: 2
当前元素: 3
当前索引: 3
当前元素: 4
当前索引: 4
当前元素: 5
修改后的列表: [2, 4, 6, 8, 10]
在代码中,enumerate(my_list)
返回一个可迭代对象,每次迭代返回一个元组(index, value)
,其中index
为当前元素的索引,value
为当前元素的值。通过修改my_list[index]
的值,可以改变列表中的元素。
上一篇:遍历动态列表