假设我有一个n=22500
和一个阈值t=10000
,我希望有一个函数可以产生:10000
,10000
,2500
。< / p>
我该怎么做?我的非工作尝试,因为一旦超过20000,它将返回大于10000的数字。
def chunk(number):
steps = 10000
if number > steps:
yield steps
yield number - steps
else:
yield number
for i in chunk(35000):
print(i)
# prints (wrongly):
# 10000
# 25000
或者是否有内置库?
答案 0 :(得分:2)
我认为这可以稍微清理一下,所以请在接下来的几分钟内检查一下编辑,但是怎么办:
def chunk(num, thresh):
while True:
if num > thresh:
num -= thresh
yield thresh
else:
yield num
break
for x in chunk(22500, 10000):
print(x)
<强>输出强>
10000 10000 2500
修改强>
考虑:
def chunk(num, thresh):
while num:
to_yield = min(num, thresh)
yield to_yield
num -= to_yield
for x in chunk(22500, 10000):
print(x)
答案 1 :(得分:2)
使用除法(floor)和模数运算符:
def chunk(number, step):
for i in range(number // step):
yield step
rem = number % step
if rem:
yield rem
for i in chunk(22500, step=10000):
print(i)
10000
10000
2500
答案 2 :(得分:1)
你需要一个循环来确保它适用于任何数量:
def chunk(number):
steps = 10000
while number > 0:
yield min(number, steps)
number -= steps
for i in chunk(35000):
print(i)
# prints:
# 10000
# 10000
# 10000
# 5000