Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...