Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
634 views
in Technique[技术] by (71.8m points)

iterator - What's the best way of skip N values of the iteration variable in Python?

In many languages we can do something like:

for (int i = 0; i < value; i++)
{
    if (condition)
    {
        i += 10;
    }
}

How can I do the same in Python? The following (of course) does not work:

for i in xrange(value):
    if condition:
        i += 10

I could do something like this:

i = 0
while i < value:
  if condition:
    i += 10
  i += 1

but I'm wondering if there is a more elegant (pythonic?) way of doing this in Python.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use continue.

for i in xrange(value):
    if condition:
        continue

If you want to force your iterable to skip forwards, you must call .next().

>>> iterable = iter(xrange(100))
>>> for i in iterable:
...     if i % 10 == 0:
...         [iterable.next() for x in range(10)]
... 
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
[41, 42, 43, 44, 45, 46, 47, 48, 49, 50]
[61, 62, 63, 64, 65, 66, 67, 68, 69, 70]
[81, 82, 83, 84, 85, 86, 87, 88, 89, 90]

As you can see, this is disgusting.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...