假设我有一个项目列表,我想遍历其中的前几个:
items = list(range(10)) # I mean this to represent any kind of iterable.
limit = 5
天真的实现
来自其他语言的 Python naïf 可能会编写这个完美的可服务和高性能(如果是非惯用的)代码:
index = 0
for item in items: # Python's `for` loop is a for-each.
print(item) # or whatever function of that item.
index += 1
if index == limit:
break
更惯用的实现
但是 Python 有枚举,它很好地包含了大约一半的代码:
for index, item in enumerate(items):
print(item)
if index == limit: # There's gotta be a better way.
break
所以我们已经将额外的代码减半了。但一定有更好的方法。
我们可以近似下面的伪代码行为吗?
如果 enumerate 采用另一个可选的 stop
参数(例如,它采用 start
这样的参数: enumerate(items, start=1)
我认为理想的是)下面不存在(请参阅 此处枚举的文档):
# hypothetical code, not implemented:
for _, item in enumerate(items, start=0, stop=limit): # `stop` not implemented
print(item)
请注意,不需要命名 index
因为不需要引用它。
有没有一种惯用的方式来写上面的内容?如何?
第二个问题:为什么不将其内置到枚举中?
原文由 Russia Must Remove Putin 发布,翻译遵循 CC BY-SA 4.0 许可协议
from itertools import izip for index, item in izip(xrange(limit), items): print(item)
for item in itertools.islice(items, 0, stop): print(item)
for index, item in enumerate(islice(items, limit)): print(index, item)
def enumerate(collection, start=0): # could add stop=None i = start it = iter(collection) while 1: # could modify to
while i != stop:
yield (i, next(it)) i += 1_enumerate = enumerate
def enumerate(collection, start=0, stop=None): if stop is not None: return zip(range(start, stop), collection) return _enumerate(collection, start)
for index, element in zip(range(limit), items): …
for index, item in enumerate(islice(items, limit)): …
for element in islice(items, 0, limit): …
”`
并避免使用下标符号进行切片,除非您了解这些限制。