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

不打扰是莪最后的温柔 提交于 2019-12-21 07:05:05

问题


So imagine I want to go over a loop from 0 to 100, but skipping the odd numbers (so going "two by two").

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?


回答1:


Use the step argument (the last, optional):

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

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

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

Range is a very powerful feature.




回答2:


(Applicable to Python <= 2.7.x only)

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.

for x in xrange(0,100,2):
    print x,   #For printing in a line

>>> 0, 2, 4, ...., 98 

Python 3 actually made range behave like xrange, which doesn't exist anymore.




回答3:


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

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

min, max, step(optional)



来源:https://stackoverflow.com/questions/27678156/how-to-count-by-twos-with-pythons-range

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!