Python列出了错误的输出

2024-10-01 13:45:26 发布

您现在位置:Python中文网/ 问答频道 /正文

下面我有代码。 在ex2ex3lst[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))

Tags: oftheaddwhichoutputisnotshows
3条回答

根据OP的评论:

Given a list of numbers, create a function which returns the list but with each element's index in the list added to itself. This means you add 0 to the number at index 0, add 1 to the number at index 1, etc...

该功能可以简单如下:

def add_indexes(lst):
    for x in range(len(lst)):
        if lst[x] += x:
    return lst

这是因为您会在运行中增加列表,在两个循环后,您会得到类似的结果:

lst = [1,3,3,4,5]

因此,条件:

elif lst[x] == lst[1]:
    lst[x] += 1

变为实数,然后将3增加1,而不是增加2。 尝试在列表副本或空列表上添加操作并附加项

原因是您首先将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]

相关问题 更多 >