What's the cleanest code that iterates on the lines of a text file, while simultaniously increamenting a counter?
I understand that with multiple assignment, there's a cleaner syntax than
i = 0
for line in f:
...
++i
for i, line in enumerate(f):
print i, line
As seen here: http://docs.python.org/library/functions.html#enumerate
for count, line in enumerate(f):
Enumerate starts at index 0 unless told otherwise providing a counter iterated at the same time as each item of your for loop
EDIT: As a side note you can change where enumerate starts from with the second argument eg for count, line in enumerate(f, 11)
would cause it to start at 11
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.