如何用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:07:44  来源:igfitidea点击:

How to count by twos with Python's 'range'

pythonrange

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

Use the step argument (the last, optional):

使用 step 参数(最后一个,可选):

for x in range(0, 100, 2):
    print(x)

Note that if you actually want to keepthe odd numbers, it becomes:

请注意,如果您确实想保留奇数,则变为:

for x in range(1, 100, 2):
    print(x)

Rangeis a verypowerfulfeature.

范围是一个非常强大的功能

回答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 rangebehave like xrange, which doesn't exist anymore.

Python 3实际上使range行为类似于xrange,它不再存在。

回答by Secret Name

for i in range(0, 100, 2):
    print i

If you are using an IDE, it tells you syntax:

如果您使用的是IDE,它会告诉您语法:

min, max, step(optional)

最小、最大、步长(可选)