python - 如何从Python 3中的for循环获得正确的结果?

标签 python python-3.x loops for-loop iteration

我正在制作一个简单的程序,其中有一个简单的 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]

最佳答案

在迭代 n 次的循环中,从起始值开始将值增加 k:

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 是起始值。您可以在代码中设置它或从用户那里读取。

关于python - 如何从Python 3中的for循环获得正确的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50923756/

相关文章:

Python 断言不工作 : limit user enter only stated numbers but assert not working

c++ - 为什么我的 while 循环永远不会结束,即使生成的整数不符合运行条件

c++ - 如何制作 C++ 程序循环的一部分?

python - 使用os.system时是否可以捕获运行时错误?

linux - 结束一个 mpirun 进程终止一个 b​​ash 循环

python - 如何从子窗口获取 GUI 主窗口中的数据?

python - 如何使用 tf.case 转换 tensorflow 中的一组值?

python - 通过 Web 界面点击并运行 docker 镜像(或 VM)?

python - 安装Jupyter笔记本的困难

python - 修复了点击 Bokeh 图元素时的 HoverTool TOOLTIPS