且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正确使用列表推导-python

更新时间:2023-11-29 08:09:04

您确实应该避免使用列表推导(以及字典推导,设置推导和生成器表达式)产生副作用.除了他们会积累虚假列表从而浪费内存这一事实之外,这也令人困惑.我希望列表理解会产生一个(有意义的)值,很多人都会同意.另一方面,循环显然是一系列语句.预计它们将开始产生副作用,并且不会产生结果值-不会感到惊讶.

You should indeed avoid using list comprehensions (along with dictionary comprehensions, set comprehensions and generator expressions) for side effects. Apart from the fact that they'd accumulate a bogus list and thus waste memory, it's also confusing. I expect a list comprehension to generate a (meaningful) value, and many would agree. Loops, on the other hand, are clearly a sequence of statements. They are expected to kick off side effects and generate no result value - no surprise.