for x in y, type iteration in python. Can I find out what iteration I'm currently on?
I have a question about the loop construct in Py开发者_开发百科thon in the form of: for x in y:
In my case y is a line read from a file and x is separate characters. I would like to put a space after every pair of characters in the output, like this: aa bb cc dd
etc. So, I would like to know the current iteration. Is it possible, or do I need to use a more traditional C style for loop with an index?
for i,x in enumerate(y):
....
Use enumerate
:
for index,x in enumerate(y):
# do stuff, on iteration #index
Alternatively, just create a variable and increment it inside the loop body. This isn't quite as 'pythonic', though.
cur = 0
for x in y:
cur += 1
# do stuff, on iteration #cur
If what you are doing is inserting a space after each pair of characters, you might want to do something with list comprehensions like:
' '.join([''.join(characterPair) for characterPair in zip(*[iter(line + ' ')] * 2)])
Without appending the extra space, the last character of lines with an odd number of characters will be dropped; with the appended space, lines with an odd number of characters will have an extra space at the end.
(There may well be a more pythonic way to do it than what I've done.)
I can't really make a case that this is better than the enumerate
method, but it is less obvious to someone coming from a C perspective, so I thought I'd point it out for completeness:
from itertools import izip_longest
' '.join(j + k for j,k in izip_longest(fillvalue='', *([iter(line)]*2)))
In Python it's often preferred (or at least encouraged) to do something with generators or list comprehensions like this, instead of relying on enumerate
.
This is a variation on the grouper
method from the itertools module documentation.
精彩评论