人们经常在 SO 上的 python 问题中找到这种类型的表达式。或者仅用于访问可迭代文件的所有项
for i in range(len(a)):
print(a[i])
这只是一种笨拙的写作方式:
for e in a:
print(e)
或者为迭代的元素赋值:
for i in range(len(a)):
a[i] = a[i] * 2
应该是相同的:
for i, e in enumerate(a):
a[i] = e * 2
# Or if it isn't too expensive to create a new iterable
a = [e * 2 for e in a]
或者过滤掉指数:
for i in range(len(a)):
if i % 2 == 1: continue
print(a[i])
可以这样表达:
for e in a [::2]:
print(e)
或者当你只需要列表的长度,而不是它的内容:
for _ in range(len(a)):
doSomethingUnrelatedToA()
可能是:
for _ in a:
doSomethingUnrelatedToA()
In python we have enumerate
, slicing, filter
, sorted
, etc... As python for
constructs are intended to iterate over iterables and not only ranges of integers, are there real-world use-cases where you need in range(len(a))
?