如何用 Python 的“范围”按二数计算
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27678156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to count by twos with Python's 'range'
提问by J. C. Rocamonde
So imagine I want to go over a loop from 0 to 100, but skipping the odd numbers (so going "two by two").
所以想象一下,我想遍历一个从 0 到 100 的循环,但跳过奇数(所以要“两个两个”)。
for x in range(0,100):
if x%2 == 0:
print x
This fixes it. But imagine I want to do so jumping two numbers? And what about three? Isn't there a way?
这修复了它。但是想象一下,我想要跳两个数字吗?那么三个呢?没有办法吗?
采纳答案by Jivan
回答by ZdaR
(Applicable to Python <= 2.7.x only)
(仅适用于 Python <= 2.7.x)
In some cases, if you don't want to allocate the memory to a list then you can simply use the xrange() function instead of the range() function. It will also produce the same results, but its implementation is a bit faster.
在某些情况下,如果您不想将内存分配给列表,那么您可以简单地使用 xrange() 函数而不是 range() 函数。它也会产生相同的结果,但它的实现速度要快一些。
for x in xrange(0,100,2):
print x, #For printing in a line
>>> 0, 2, 4, ...., 98
Python 3actually made range
behave like xrange
, which doesn't exist anymore.
Python 3实际上使range
行为类似于xrange
,它不再存在。