首页 > 解决方案 > 如何从 Python 3 中的 for 循环中获得正确的结果?

问题描述

我正在制作一个简单的程序,其中有一个简单的for循环。我的程序中有两个输入,nkk用于在迭代中跳过数字,n是要打印的数字的数量。

这是我的代码:

nk = input().split()
n = int(nk[0])
k = int(nk[1])
store_1 = []
for x in range(1,n+n,k):
    store_1.append(x)
print(store_1)

似乎唯一有效的对是当 k 设置为 2 并且范围的起点保持为 1 时。但是当 k 设置为任何其他数字并且范围的起点高于 1 时,它不会提供正确的输出. 例如:

#6 and 3, starting range 1
[1,4,7,10]
#Correct output: [1,4,7,10,13,16]

#4 and 2, starting range 2
[2,4,6]
#Correct output: [2,4,6,8]

#4 and 2, starting range 1
[1,3,5,7]
Only this sort of pair and starting range provides the correct output.

如何修复我的代码并获得正确的输出。注意:我可以将范围的开始设置为任何数字,例如:2、3、4 等。

编辑:更多样本:

#5 and 3, starting range 3
Correct output: [3,6,9,12,15]
#7 and 7, starting range 1
Correct output: [1, 8, 15, 22, 29, 36, 43]
#6 and 8, starting range 5
Correct output: [5,13,21,29,37,45]

标签: pythonpython-3.xloopsfor-loopiteration

解决方案


通过在迭代次数k的循环中从起始值开始递增值:n

n, k = list(map(int, input().split()))
store_1, x = [], 1  # x is the starting range.
for _ in range(n):
    store_1.append(x)
    x += k
print(store_1)

请注意,这x是起始值。您可以在代码中设置它,也可以从用户那里读取。


推荐阅读