尝试在此单行循环中增加 Y

Trying to increment Y in this single line loop

我需要递增 Y,以便在将 Y 添加到数组中的值时,它会依次添加 1、2、3。

尝试 运行 在单行上方循环,但我遇到了问题,出于某种原因,在列表中添加值对我来说很挑剔。

answer = [5,8,13,16]
y=0
new_arr = [y+x for x in answer]

预期产出

new_arr = [5, 9, 15, 19]

enumerate 运行索引和迭代值:

answer = [5,8,13,16]
new_arr = [y+x for y, x in enumerate(answer)]

输出:

[5, 9, 15, 19]

与其尝试使 y 成为一个常规数字,不如尝试将其作为一个包含值 [0, 1, 2, 3...] 的列表并将其添加到原始列表中。

下面的代码应该可以满足您的需求:

# The input
x = [5,8,13,16]

# An array containing [0, 1, 2, 3, ... len(x) - 1 ] with the exact size of the input
y = range(len(x))

# Iterate on both arrays, adding entries one by one
answer = [(z[0] + z[1]) for z in zip(x, y)]

print(answer)

输出:

[5, 9, 15, 19]

作为奖励,对于该解决方案,使用 numpynp.arrange,您将获得大多数 python 程序员都能理解的真正可读代码:

import numpy as np

x = [5,8,13,16]
y = np.arange(len(x))
answer = x + y

print(answer)

输出:

[5 9 15 19]

到目前为止有两个很好的答案,但添加第三个只是为了多样性,加载模块和调用 next 方法时成本更高。但添加 none the less 作为另一种选择。

from itertools import count
answer = [5,8,13,16]
y=count(0)
new = [x + next(y) for x in answer]
print(new)

输出

[5, 9, 15, 19]