如何从Python3中的for循环中获得正确的结果?
我正在制作一个简单的程序,其中有一个简单的如何从Python3中的for循环中获得正确的结果?,python,python-3.x,loops,for-loop,iteration,Python,Python 3.x,Loops,For Loop,Iteration,我正在制作一个简单的程序,其中有一个简单的for循环。我的程序中有两个输入,n和kk用于在迭代过程中跳过数字,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被设置为任何其他数字并且范围的起
for
循环。我的程序中有两个输入,n和kk用于在迭代过程中跳过数字,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
是起始值。您可以在代码中设置它,也可以从用户处读取。另一个源于您的解决方案,使用while循环:
nk = input().split() #Example of entry 2 6
n = int(nk[0])
k = int(nk[1])
store1=[]
stored_num = 1
count_of_printed_nums = 0
while(count_of_printed_nums<n):
store1.append(stored_num)
stored_num+=k
count_of_printed_nums+=1
print(store1)
nk=input().split()#条目2的示例6
n=int(nk[0])
k=int(nk[1])
store1=[]
存储数量=1
打印数量的计数=0
而(打印数量)的智能方法是:
n, k, s = list(map(int, input().split())) # s is the start_range
store_1 = list(range(s,s+(n*k),k))
print(store_1)
样本输入:
5 3 3
输出:
[3,6,9,12,15]
不错。但是你需要Python 3中的list()
range
。同意!:)谢谢@Austin