Python idiom for loop cycle calculation

If the loop is in a list / tuple / sequence, you can use len(...)to determine how many times the loop has been executed. But when going through an iterator, you cannot.

[Update for clarity: I am thinking of single-user end iterators, where I want to do element calculations and count them at the same time.]

I am currently using an explicit counter variable, as in the following example:

def some_function(some_argument):
    pass


some_iterator = iter("Hello world")

count = 0
for value in some_iterator:
    some_function(value)
    count += 1

print("Looped %i times" % count)

Given that "Hello world"there are 11 characters in, the expected result is here:

Looped 11 times

I also considered this shorter alternative using enumerate(...), but I don't find it clear:

def some_function(some_argument):
    pass


some_iterator = iter("Hello world")

count = 0  # Added for special case, see note below
for count, value in enumerate(some_iterator, start=1):
    some_function(value)

print("Looped %i times" % count)

[ : @mata , , , , . count = 0 , for ... else ... .]

enumerate(...) , , , . , .

Pythonic ( Python 3 Python 2)?

+4
4

enumerate , , :

count = 0  # Counter is set in any case.
for count, item in enumerate(data, start=1):
   doSomethingTo(item)
print "Did it %d times" % count

, , :

count = sum(1 for ignored_item in data)  # count a 1 for each item
+5

, . , .

length = sum(1 for x in gen)
length = max(c for c, _ in enumerate(gen, 1))
length = len(list(gen))
  • , , , , .
  • , , , , , , , .
  • , , , , gen, , , , , , .

.

"" , :

length = 0
for length, data in enumerate(gen, 1):
    # do stuff

length , . , length , length, data .


EDIT: ( , ), :

length = sum(1 | bool(function(x)) for x in gen)

function . enumerate .

+2

.

def gen():
   a = 1
   while True:
       yield a
       a += 1
f = gen()

for value in f:
    # do something

? , , a StopIteration. , , , .

, , . . -

from itertools import count
for item, counter in zip(iterator, count()):
    # do stuff

However, I think in most cases your first, traditional approach would be clearer.

+1
source

What is wrong with that?

len(list(some_iterator))
0
source

Source: https://habr.com/ru/post/1669596/


All Articles