>>> 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
这只是一些简单的数学:
给我们:
^{pr2}$这里我们使用the ^{} builtin 和list comprehension。在
这是通过使用}的生成器,采取
range()
构建一个从1
到{x
除以y
的步骤。在然后我们使用列表理解来获取这些值(
1, 1001, 2001, ..., 9001
),然后将它们放入元组对中,将(x//y-1)
(在本例中是999
)添加到值中以获得结束边界。在当然,如果你想在一个循环中使用它,你最好使用一个生成器表达式,这样它就可以懒洋洋地计算,而不是列表理解。E、 g组:
相关问题 更多 >
编程相关推荐