在 Python 中,使用列表推导式还是 for-each 循环更好? [英] In Python, is it better to use list comprehensions or for-each loops?

查看:30
本文介绍了在 Python 中,使用列表推导式还是 for-each 循环更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下哪个更好用?为什么?

Which of the following is better to use and why?

方法一:

for k, v in os.environ.items():
       print "%s=%s" % (k, v)

方法二:

print "
".join(["%s=%s" % (k, v) 
   for k,v in os.environ.items()])

我倾向于倾向于第一个更容易理解,但这可能只是因为我是 Python 的新手并且列表推导式对我来说仍然有些陌生.第二种方式被认为更 Pythonic 吗?我假设没有性能差异,但我可能是错的.这两种技术的优缺点是什么?

I tend to lead towards the first as more understandable, but that might just be because I'm new to Python and list comprehensions are still somewhat foreign to me. Is the second way considered more Pythonic? I'm assuming there's no performance difference, but I may be wrong. What would be the advantages and disadvantages of these 2 techniques?

(代码取自 深入 Python)

(Code taken from Dive into Python)

推荐答案

如果迭代是为了它的副作用(就像在打印"示例中那样),那么循环会更清晰.

If the iteration is being done for its side effect ( as it is in your "print" example ), then a loop is clearer.

如果执行迭代是为了构建复合值,那么列表推导式通常更具可读性.

If the iteration is executed in order to build a composite value, then list comprehensions are usually more readable.

这篇关于在 Python 中,使用列表推导式还是 for-each 循环更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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