python 生成器表达式
The list is a collection of different types of elements and there are many ways of creating a list in Python.
该列表是不同类型元素的集合,并且有许多方法可以在Python中创建列表。
清单理解 (List Comprehension)
List comprehension is one of the best ways of creating the list in one line of Python code. It is used to save a lot of time in creating the list.
列表理解是在一行Python代码中创建列表的最佳方法之一。 它用于节省创建列表的大量时间。
Let's take an example for a better understanding of the list comprehension that calculates the square of numbers up to 10. First, we try to do it by using the for loop and after this, we will do it by list comprehension in Python.
让我们以一个示例为例,以更好地理解列表推导,该推导可以计算最多10个数字的平方。首先,我们尝试使用for循环进行此操作,然后,在Python中通过列表推导进行此操作。
By using the for loop:
通过使用for循环:
List_of_square=[]
for j in range(1,11):
s=j**2
List_of_square.append(s)
print('List of square:',List_of_square)
Output
输出量
List of square: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Now, we do it by List comprehension,
现在,我们通过列表理解来做到这一点,
List_of_square=[j**2 for j in range(1,11)]
print('List of square:',List_of_square)
Output
输出量
List of square: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
As we have seen that the multiple lines of code of for loop gets condensed into one line of code in the list comprehension and also saves the execution time.
如我们所见,for循环的多行代码在列表理解中被压缩为一行代码,还节省了执行时间。
生成器表达式 (Generator Expression)
A generator expression is slightly similar to list comprehension but to get the output of generators expression we have to iterate over it. It is one of the best ways to use less memory for solving the same problem that takes more memory in the list compression. Here, a round bracket is used instead of taking output in the form of the list. Let’s look at an example for a better understanding of generator expression that will calculate the square of even numbers up to 20.
生成器表达式与列表理解有些相似,但是要获得生成器表达式的输出,我们必须对其进行迭代。 这是使用较少的内存来解决相同的问题(在列表压缩中占用更多内存)的最佳方法之一。 在此,使用圆括号代替列表形式的输出。 让我们看一个示例,以更好地理解生成器表达式,该表达式将计算最多20个偶数的平方。
Program:
程序:
generators_expression=(j**2 for j in range(1,21) if j%2==0)
print('square of even number:')
for j in generators_expression:
print(j, end=' ')
Output
输出量
square of even number:
4 16 36 64 100 144 196 256 324 400
翻译自: https://www.includehelp.com/python/list-comprehension-vs-generators-expression.aspx
python 生成器表达式