首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python平均拆分

Python平均拆分
EN

Stack Overflow用户
提问于 2012-05-13 19:56:18
回答 1查看 168关注 0票数 0

这可能有点傻。我现在想不出来了。

有一个总数(x)

它需要用(y)平分

如果x是10,000,y是10,

这意味着10,000将被吐在10之间。

如何找到起始点

代码语言:javascript
运行
复制
1 starts at 1 and ends 1,000
2 starts at 1,001 & ends 2,000
3 ..
4 ..
5 ..
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-05-13 20:02:16

这只是一些简单的数学运算:

代码语言:javascript
运行
复制
x = 10000
y = 10
print([(item, item+(x//y-1)) for item in range(1, x, x//y)])

为我们提供了:

代码语言:javascript
运行
复制
[(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()内建构造一个从1x以下的生成器,采用x除以y (整数除法,所以我们不会得到浮点数)的步骤来实现的。

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

当然,如果您想在循环中使用它,例如,您最好使用生成器表达式,以便延迟计算它,而不是列表理解。例如:

代码语言:javascript
运行
复制
>>> 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
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10571505

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档