问题
Could you please tell me why it is considered as "not pythonic" when I need the index and the value when looping over a list and use:
a = [1,2,3]
for i in range(len(a)):
# i is the idx
# a[i] is the value
but rather it is recommended to use
for idx, val in enumerate(a):
print idx, val
who defines "pythonic" and why is the latter one better? I mean it's not that much better concerning readability, is it!?
Thanks in advance
回答1:
First of all, the first way is ugly: You either need a separate variable assignment to get the element or use a[i]
all the time which could theoretically be an expensive operation. Imagine a
being a database cursor: When you iterate it (a.__iter__
being called) the object can safely assume that you are going to iterate over all its items. So all or at least multiple rows could be retrieved at once. When getting the length such an optimization would be stupid though since you surely don't want to retrieve data just because you want the number of items. Also, when retrieving a specific item you cannot assume that other items will be retrieved, too.
Additionally, using enumerate()
works with any iterable while range(len())
only works with countable, indexable objects.
来源:https://stackoverflow.com/questions/24150762/pythonic-range-vs-enumerate-in-python-for-loop