[英]Creating a list of evenly divisible numbers with a different divider on each iteration of a for loop
first question on stackOverflow :) !关于stackOverflow的第一个问题:)! I would like to divide the range list by a different divider on each iteration of the for loop: For that I thought about having
x
change on each iteration.我想在 for 循环的每次迭代中用不同的分隔符来划分范围列表:为此,我想在每次迭代中更改
x
。 I tried different things like making x
a list,and multiple other improvised ways, but to no avail.我尝试了不同的事情,比如将
x
一个列表,以及其他多种即兴方式,但无济于事。 I have no idea why the code seems to iterate correctly but the value of x
doesn't change with x -= 1
.我不知道为什么代码似乎正确迭代,但
x
的值不会随x -= 1
改变。
The ultimate goal is to compare those lists and find similar evenly divisible numbers.最终目标是比较这些列表并找到相似的可整除数。 But one thing at a time...
但一次做一件事...
Here is the code:这是代码:
def divisible(x):
lst1 = []
while x >= 2:
for each in range(0, 100001, 20):
if each % x == 0:
lst1.append(each)
x -= 1
return lst1
print(divisible(19))
It prints the first value of x
only:它只打印
x
的第一个值:
[0, 380, 760, 1140, 1520, 1900, 2280, 2660, 3040, 3420, 3800, 4180, 4560, 4940...etc]
The issue is that your return statement is inside the while loop, which means that your function returns after the first iteration;问题是您的 return 语句在 while 循环内,这意味着您的函数在第一次迭代后返回; preventing more iterations.
防止更多的迭代。 Making this small modification results in this code:
进行这个小的修改会产生以下代码:
def divisible(x):
lst1 = []
while x >= 2:
for each in range(0, 100001, 20):
if each % x == 0:
lst1.append(each)
x -= 1
return lst1
print(divisible(19))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.