Pythonic:range在python for循环中枚举 [英] Pythonic: range vs enumerate in python for loop

查看:291
本文介绍了Pythonic:range在python for循环中枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能告诉我为什么当我需要索引和值,当循环列表和使用时被认为是不是pythonic的:

  a = [1,2,3] 
for i in range(len(a)):
#i是idx
#a [i]值

,但建议使用

  for idx,val in enumerate(a):
print idx,val

谁定义pythonic,为什么后者更好?



提前感谢

解决方案

首先,第一种方式是丑陋的:你需要一个单独的变量赋值来获取元素或使用 a [i] 这在理论上可能是昂贵的操作。想象一下 a 作为数据库游标:当你迭代它( a .__ iter __ 被调用)时,对象可以安全地假设你将要遍历所有的项目。因此,可以一次检索所有或至少多个行。当获得长度这样的优化将是愚蠢的,因为你肯定不想检索数据,因为你想要的项目数。



此外,使用 enumerate()适用于任何可迭代对象 range(len())只适用于 / p>

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

解决方案

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.

这篇关于Pythonic:range在python for循环中枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆