Python平分

2024-06-02 12:34:12 发布

您现在位置:Python中文网/ 问答频道 /正文

这可能很傻。我现在想不出来。在

有一个总数(x)

它需要与(y)平分

如果x是10000,y是10

那就意味着10点之间就有1万人。在

如何找到起点

1 starts at 1 and ends 1,000
2 starts at 1,001 & ends 2,000
3 ..
4 ..
5 ..

Tags: andat起点总数starts平分ends
1条回答
网友
1楼 · 发布于 2024-06-02 12:34:12

这只是一些简单的数学:

x = 10000
y = 10
print([(item, item+(x//y-1)) for item in range(1, x, x//y)])

给我们:

^{pr2}$

这里我们使用the ^{} builtinlist comprehension。在

这是通过使用range()构建一个从1到{}的生成器,采取x除以y的步骤。在

然后我们使用列表理解来获取这些值(1, 1001, 2001, ..., 9001),然后将它们放入元组对中,将(x//y-1)(在本例中是999)添加到值中以获得结束边界。在

当然,如果你想在一个循环中使用它,你最好使用一个生成器表达式,这样它就可以懒洋洋地计算,而不是列表理解。E、 g组:

>>> 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

相关问题 更多 >