首先,最重要的是:Python
for循环与C
for循环实际上并不是同一回事。它们改为For
Each循环。您迭代一个可迭代的元素。
range()生成一个可迭代的整数序列,让您模拟最常见的C
for循环用例。
然而,大多数的时候你 不 希望使用
range()。您将遍历列表本身:
for elem in reversed(some_list): # elem is a list value
如果必须具有索引,通常
enumerate()可以将其添加到循环中:
for i, elem in reversed(enumerate(some_list)): # elem is a list value, i is it's index in the list
对于真正的“笨拙”循环,请使用
while或创建自己的生成器函数:
def halved_loop(n): while n > 1: yield n n //= 2for i in halved_loop(10): print i
打印
10,
5,
2。您也可以将其扩展到序列:
def halved_loop(sequence): n = -1 while True: try: yield sequence[n] except IndexError: return n *= 2for elem in halved_loop(['foo', 'bar', 'baz', 'quu', 'spam', 'ham', 'monty', 'python']): print elem
打印:
pythonmontyspamfoo



