python 生成器表达式_Python中的列表理解与生成器表达式
python 生成器表達(dá)式
The list is a collection of different types of elements and there are many ways of creating a list in Python.
該列表是不同類型元素的集合,并且有許多方法可以在Python中創(chuàng)建列表。
清單理解 (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代碼中創(chuàng)建列表的最佳方法之一。 它用于節(jié)省創(chuàng)建列表的大量時(shí)間。
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.
讓我們以一個(gè)示例為例,以更好地理解列表推導(dǎo),該推導(dǎo)可以計(jì)算最多10個(gè)數(shù)字的平方。首先,我們嘗試使用for循環(huán)進(jìn)行此操作,然后,在Python中通過列表推導(dǎo)進(jìn)行此操作。
By using the for loop:
通過使用for循環(huán):
List_of_square=[]for j in range(1,11):s=j**2List_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,
現(xiàn)在,我們通過列表理解來做到這一點(diǎn),
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循環(huán)的多行代碼在列表理解中被壓縮為一行代碼,還節(jié)省了執(zhí)行時(shí)間。
生成器表達(dá)式 (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.
生成器表達(dá)式與列表理解有些相似,但是要獲得生成器表達(dá)式的輸出,我們必須對(duì)其進(jìn)行迭代。 這是使用較少的內(nèi)存來解決相同的問題(在列表壓縮中占用更多內(nèi)存)的最佳方法之一。 在此,使用圓括號(hào)代替列表形式的輸出。 讓我們看一個(gè)示例,以更好地理解生成器表達(dá)式,該表達(dá)式將計(jì)算最多20個(gè)偶數(shù)的平方。
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 生成器表達(dá)式
總結(jié)
以上是生活随笔為你收集整理的python 生成器表达式_Python中的列表理解与生成器表达式的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 颐和园外地车辆能进吗
- 下一篇: Python程序可打印今天的年,月和日