python - 如何从 Python 3 中的 for 循环中获得正确的结果?
问题描述
我正在制作一个简单的程序,其中有一个简单的for
循环。我的程序中有两个输入,n和k。k用于在迭代中跳过数字,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]
解决方案
通过在迭代次数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
是起始值。您可以在代码中设置它,也可以从用户那里读取。
推荐阅读
- image - 在 Image REACT NATIVE 上遇到 onError 时替换为文本
- angular - Angular 6 / 7 / 8 ngbtypeahead 返回匹配和不匹配的记录
- apache - 重定向到新域,缺少 Post 值
- android - 如何在kotlin的string.xml中使用字符串模板
- python - ImportError:无法从“sklearn.decomposition._online_lda”导入名称“LatentDirichletAllocation”
- react-native - 从原生组件导航到 React Native 组件
- symfony - 切片树枝路径
- javascript - 每次创建新的 chrome 窗口时如何运行脚本?
- javascript - 为什么不刷新页面就不会删除数据表中的数据?
- jhipster - 我可以在远程服务器 (Docker) 中使用共享的 jhipster-registry 和 uaa,开发人员可以将其作为服务连接吗?