这可能有点傻。我现在想不出来了。
有一个总数(x)
它需要用(y)平分
如果x是10,000,y是10,
这意味着10,000将被吐在10之间。
如何找到起始点
1 starts at 1 and ends 1,000
2 starts at 1,001 & ends 2,000
3 ..
4 ..
5 ..
发布于 2012-05-13 20:02:16
这只是一些简单的数学运算:
x = 10000
y = 10
print([(item, item+(x//y-1)) for item in range(1, x, x//y)])
为我们提供了:
[(1, 1000), (1001, 2000), (2001, 3000), (3001, 4000), (4001, 5000), (5001, 6000), (6001, 7000), (7001, 8000), (8001, 9000), (9001, 10000)]
这里我们使用the range()
builtin和一个list comprehension。
这是通过使用range()
内建构造一个从1
到x
以下的生成器,采用x
除以y
(整数除法,所以我们不会得到浮点数)的步骤来实现的。
然后,我们使用列表理解来获取这些值(1, 1001, 2001, ..., 9001
),然后将它们放入元组对中,将(x//y-1)
(在本例中为999
)添加到值中以获得结束边界。
当然,如果您想在循环中使用它,例如,您最好使用生成器表达式,以便延迟计算它,而不是列表理解。例如:
>>> for number, (start, end) in enumerate((item, item+(x//y-1)) for item in range(1, x, x//y)):
... print(number, "starts at", start, "and ends at", end)
...
0 starts at 1 and ends at 1000
1 starts at 1001 and ends at 2000
2 starts at 2001 and ends at 3000
3 starts at 3001 and ends at 4000
4 starts at 4001 and ends at 5000
5 starts at 5001 and ends at 6000
6 starts at 6001 and ends at 7000
7 starts at 7001 and ends at 8000
8 starts at 8001 and ends at 9000
9 starts at 9001 and ends at 10000
https://stackoverflow.com/questions/10571505
复制相似问题