正确使用列表推导-python [英] proper use of list comprehensions - python
问题描述
通常,列表推导用于从现有列表中派生新列表.例如:
Normally, list comprehensions are used to derive a new list from an existing list. Eg:
>>> a = [1, 2, 3, 4, 5]
>>> [i for i in a if i > 2]
[3, 4, 5]
我们应该使用它们执行其他过程吗?例如:
Should we use them to perform other procedures? Eg:
>>> a = [1, 2, 3, 4, 5]
>>> b = []
>>> [b.append(i) for i in a]
[None, None, None, None, None]
>>> print b
[1, 2, 3, 4, 5]
还是应该避免上述情况,而是使用以下内容?
or should I avoid the above and use the following instead?:
for i in a:
b.append(i)
推荐答案
您确实应该避免使用列表推导(以及字典推导,设置推导和生成器表达式)产生副作用.除了他们会积累虚假列表从而浪费内存这一事实之外,这也令人困惑.我希望列表理解会产生一个(有意义的)值,很多人都会同意.另一方面,循环显然是一系列语句.预计它们将开始产生副作用,并且不会产生结果值-不会感到惊讶.
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.
这篇关于正确使用列表推导-python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!