下面我有代码。
在ex2
和ex3
,lst[2]
和lst[3]
显示不同的输出。
例如:
At ex3, lst[2] shows the output of 5 which is correct but
at ex2, lst[2] shows the output of 4 which is not correct because lst[2] should be added by 2, not by one
为什么呢?我打错了什么? 我是python新手,所以任何帮助都很好。 谢谢
def add_indexes(lst):
for x in range(len(lst)):
if lst[x] == lst[0]:
lst[x] += 0
elif lst[x] == lst[1]:
lst[x] += 1
elif lst[x] == lst[2]:
lst[x] += 2
elif lst[x] == lst[3]:
lst[x] += 3
elif lst[x] == lst[4]:
lst[x] += 4
return lst
ex1 = [0, 0, 0, 0, 0]
ex2 = [1, 2, 3, 4, 5]
ex3 = [5, 4, 3, 2, 1]
print(add_indexes(ex1))
print(add_indexes(ex2))
print(add_indexes(ex3))
根据OP的评论:
该功能可以简单如下:
这是因为您会在运行中增加列表,在两个循环后,您会得到类似的结果:
因此,条件:
变为实数,然后将3增加1,而不是增加2。 尝试在列表副本或空列表上添加操作并附加项
原因是您首先将lst[1]的值从2更新为3,这意味着在下一次迭代中,lst[1]==lst[2]将被应用
开始
迭代0:
迭代1:
迭代2:
对于您的需求,您可以简单地使用列表理解:
输出:
相关问题 更多 >
编程相关推荐