当您遍历循环时,您是在遍历循环元素而不是索引。您需要使用
enumerate来获取索引和值。
一个小演示可以
def modifyValues(l): for i,x in enumerate(l): # Use enumerate here. if x == 1: l[i] = 'a' elif x == 2: l[i] = 'b' elif x == 3: l[i] = 'c' print (l)
输出量
['a', 'b', 'c', 'b', 'c', 'a', 'b', 'b']

当您遍历循环时,您是在遍历循环元素而不是索引。您需要使用
enumerate来获取索引和值。
一个小演示可以
def modifyValues(l): for i,x in enumerate(l): # Use enumerate here. if x == 1: l[i] = 'a' elif x == 2: l[i] = 'b' elif x == 3: l[i] = 'c' print (l)
输出量
['a', 'b', 'c', 'b', 'c', 'a', 'b', 'b']