Python列出了错误的输出
下面我有代码。 在Python列出了错误的输出,python,list,Python,List,下面我有代码。 在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新手,所以任何帮助都很好。 谢谢 我建议用
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新手,所以任何帮助都很好。
谢谢
我建议用另一种方法来做-
[np.sum(i) for i in enumerate(ex2)]
[np.sum(i) for i in enumerate(ex2)]
原因是您首先将lst[1]的值从2更新为3,这意味着在下一次迭代中,lst[1]==lst[2]将被应用 开始
lst = [1,2,3,4,5]
迭代0:
x=0 => nothing changes
迭代1:
x=1 => lst[1] == lst[1] => lst[1]+=1 => lst[1] =3
迭代2:
x=2 => lst[2] == lst[1] => lst[2]+=1 => lst[2] =3
对于您的需求,您可以简单地使用列表理解:
ex2 = [1, 2, 3, 4, 5]
result = [x+ind for ind, x in enumerate(ex2)]
输出:
>>> result
[1, 3, 5, 7, 9]
错误:
您正在以迭代方式更改值,因此当x=2时,lst[1]已经是3,因此它只将1添加到lst[2]
我想你是想根据他们在列表中的位置来添加数字。您可以简单地执行以下操作:
ex1=[0,0,0,0,0]
对于范围内的i(len(ex1)):
ex1[i]+=i
打印(ex1)
输出:
[0, 1, 2, 3, 4]
这是因为您会在运行中增加列表,在两个循环后,您会得到类似的结果:
lst = [1,3,3,4,5]
因此,条件:
elif lst[x] == lst[1]:
lst[x] += 1
变为实数,然后将3增加1,而不是增加2。
尝试在列表副本或空列表上添加操作并附加项目。来自OP的评论:
给定一个数字列表,创建一个函数,返回列表,但
将列表中每个元素的索引添加到自身中。这意味着你
将0添加到索引0处的数字,将1添加到索引1处的数字,
等等
该功能可以简单如下:
def add_indexes(lst):
for x in range(len(lst)):
if lst[x] += x:
return lst
我在这里看到了很多正确的答案,但我想指出你犯的错误
从我所看到的情况来看,您正在尝试检查列表中索引的每个单独情况,并将相应的索引添加到存储在该特定列表中的值中。 从这个角度考虑,您选择的“如果”条件:
if lst[x] == lst[0]:
elif lst[x] == lst[1]:
elif lst[x] == lst[2]:
elif lst[x] == lst[3]:
elif lst[x] == lst[4]:
这将检查当前索引的值是否与每个索引的值相等。这使得列表变得动态,正如@CanciuCostin所解释的那样
正确的方法如下所示:
for x in range(len(lst)):
if x == 0:
lst[x] += 0
elif x == 1:
lst[x] += 1
elif x == 2:
lst[x] += 2
elif x == 3:
lst[x] += 3
elif x == 4:
lst[x] += 4
但这是一种低效的方法。感谢@Sai Sreenivas改进了高效的代码来解决您的问题。我不明白代码应该做什么,或者为什么结果应该是有意义的。我有一项任务需要:给定一个数字列表,创建一个函数,返回列表,但将列表中每个元素的索引添加到自身。这意味着您将0添加到索引0处的数字,将1添加到索引1处的数字,等等。“@Arimmjow:您的代码不符合您的描述。您不需要执行任何测试(if语句)。只需在列表范围内循环,然后添加
lst[x]+=x
。
def add_indexes(lst):
for x in range(len(lst)):
if lst[x] += x:
return lst
if lst[x] == lst[0]:
elif lst[x] == lst[1]:
elif lst[x] == lst[2]:
elif lst[x] == lst[3]:
elif lst[x] == lst[4]:
for x in range(len(lst)):
if x == 0:
lst[x] += 0
elif x == 1:
lst[x] += 1
elif x == 2:
lst[x] += 2
elif x == 3:
lst[x] += 3
elif x == 4:
lst[x] += 4