如果不分配列表理解,效率如何? [英] How (in)efficient is a list comprehension if you don't assign it?

查看:59
本文介绍了如果不分配列表理解,效率如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个问题中,我正在与一个对此进行评论的评论员争执

In this question, I'm having an argument with a commenter who argues that

for t in threads:
    t.join()

会比

[t.join() for t in threads]

不考虑滥用理解力"的问题-我倾向于同意,但是我希望这是一句话:我的版本(第二个)的效率(效率)到底是多少?在我的情况下,Python会始终实现列表理解吗?还是在内部使用生成器?

Leaving the matter of "abusing comprehensions" aside - I tend to agree but I would like a one-liner for this: How (in-)efficient is my version (the second one) really?. Does Python materialize list comprehensions always / in my case or does it use a generator internally?

map(lambda t: t.join(), threads)会更有效吗?还是有另一种方法将功能应用于列表threads中的每个元素?

Would map(lambda t: t.join(), threads) be more efficient? Or is there another way to apply the function to each element in the list threads?

推荐答案

列表理解将总是 生成列表对象,在这种情况下,列表对象具有所有t.join()调用的返回值.因此,Python为您生成长度为len(threads)None值的列表. Python绝不会尝试优化列表对象的创建.

A list comprehension will always produce a list object, in this case with the return values of all the t.join() calls. Python thus produces as list with None values of length len(threads) for you. Python will never try to optimize away the list object creation.

使用map()的效率也不高,因为您在lambda中添加了其他堆栈推入.只需坚持明确的for循环.

Using map() is also not any more efficient as you add additional stack pushes with the lambda. Just stick with the explicit for loop.

确实,对于一系列线程连接,尝试在此处进行微优化没有毫无意义. 对于非关键的代码,您的可读性受到了损害.

Really, for a series of thread joins there is no point in trying to micro optimize here. You are hurting readability for a non-critical piece of code.

换句话说,我完全同意评论者的意见.不要仅出于副作用而使用列表推导或map(),而不必自己按 ENTER 并创建两行代码.

In other words, I entirely agree with the commenter. Do not use a list comprehension or map() just for the side effects and saving yourself having to hit ENTER and create two lines of code.

引用 Python禅宗:

  • 可读性计数.
  • Readability counts.

这篇关于如果不分配列表理解,效率如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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