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 生成器表達式