本文介绍了为什么有时会不理解python列表理解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我遇到的许多开发人员都建议最好的做法是使用简单的循环,并使用条件而不是一行列表的理解语句.

Many developers I have met suggest it's best practice to go with simple loops and if conditions instead of one line list comprehension statements.

我一直发现它们非常强大,因为我可以在一行中放入很多代码,并且可以避免创建大量变量.为什么它仍然被认为是不好的做法?

I have always found them very powerful as I can fit a lot of code in a single line and it saves a lot of variables from being created. Why is it still considered a bad practice?

(慢吗?)

推荐答案

列表推导用于创建列表,例如:

List comprehensions are used for creating lists, for example:

squares = [item ** 2 for item in some_list]

For循环更适合对列表(或其他对象)的元素做某事:

For loops are better for doing something with the elements of a list (or other objects):

for item in some_list:
    print(item)

通常不理解使用它的副作用,或者使用for循环来创建列表.

Using a comprehension for its side effects, or a for-loop for creating a list, is generally frowned upon.

这里的其他一些答案主张一旦理解时间过长,就将理解力转变为循环.我认为这不是很好的样式:创建列表所需的append调用仍然很丑陋.而是重构为一个函数:

Some of the other answers here advocate turning a comprehension into a loop once it becomes too long. I don't think that's good style: the append calls required for creating a list are still ugly. Instead, refactor into a function:

def polynomial(x):
    return x ** 4 + 7 * x ** 3 - 2 * x ** 2 + 3 * x - 4
result = [polynomial(x) for x in some_list]

仅当您担心速度时-并且已经完成了性能分析! –您应该保持冗长且难以理解的列表理解.

Only if you're concerned about speed – and you've done your profiling! – you should keep the long, unreadable list comprehension.

这篇关于为什么有时会不理解python列表理解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 10:27