for with counter
Possible Duplicate:
Accessing the index in Python for loops
I wonder: does Python have something like?
for (i=0; i < length; i += 1){ .... }
Of course, I might say
i = 0
for item in items:
#.....
i += 1
but I think there should be something similar to for(i = 0;...)
, shouldn't it?
Use the enumerate()
function:
for i, item in enumerate(items):
print i, item
or use range()
:
for i in range(len(items)):
print i
(On python 2 you'd use xrange()
instead).
range()
let's you step through i
in steps other than 1
as well:
>>> list(range(0, 5, 2))
[0, 2, 4]
>>> list(range(4, -1, -1))
[4, 3, 2, 1, 0]
You usually don't need to use an index for sequences though; not with the itertools
library or the reversed()
function; most usecases for 'special' index value ranges are covered:
>>> menu = ['spam', 'ham', 'eggs', 'bacon', 'sausage', 'onions']
>>> # Reversed sequence
>>> for dish in reversed(menu):
... print(dish)
...
onions
sausage
bacon
eggs
ham
spam
>>> import itertools
>>> # Only every third
>>> for dish in itertools.islice(menu, None, None, 3):
... print(dish)
...
spam
bacon
>>> # In groups of 4
>>> for dish in itertools.izip_longest(*([iter(menu)] * 4)):
... print(dish)
...
('spam', 'ham', 'eggs', 'bacon')
('sausage', 'onions', None, None)
Attempt for that this is a deliberate language choice. The majority of times does loop through numbers in lower level languages, those numbers are used as indexes in a sequence. For the cases one does actually needs the numbers, one should use the range
built-in function - which returns an iterable with the desired range([start], end, [step])
input values.
More often, one does need both the items of a sequence and their index, in this case, one should use the builtn enumerate
instead:
for index, letter in enumerate("word"):
print index, letter
And finally, in C and derived languages (Java, PHP, Javascript, C#, Objective C), the for
Syntax is just some (very rough) syntax sugar to a while loop - and you can just write the same while loop in Python.
Instead of: for (start_expr, check_expr, incr_expr) { code_body}
you do:
start_expr
while check_expr:
code_body
incr_expr
It works exactly the same.
for i in range(length):
#do something
什么range
是。
上一篇: 使用序列号在Python中打印列表
下一篇: 与柜台