python入門第十六天__列表產生式

來源:互聯網
上載者:User

標籤:函數   stc   lin   false   三層   TE   產生式   turn   多個   

列表產生式即List Comprehensions,是Python內建的非常簡單卻強大的可以用來建立list的產生式。

舉個例子,要產生list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]可以用list(range(1, 11))

>>> list(range(1, 11))[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

但如果要產生[1x1, 2x2, 3x3, ..., 10x10]怎麼做?方法一是迴圈:

>>> L = []>>> for x in range(1, 11):...    L.append(x * x)...>>> L[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

但是迴圈太繁瑣,而列表產生式則可以用一行語句代替迴圈產生上面的list:

>>> [x * x for x in range(1, 11)][1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
def f(n):    return n*n*na=list(f(x) for x in range(10))print(a)

產生結果:

[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]

寫列表產生式時,把要產生的元素x * x放到前面,後面跟for迴圈,就可以把list建立出來,十分有用,多寫幾次,很快就可以熟悉這種文法。

for迴圈後面還可以加上if判斷,這樣我們就可以篩選出僅偶數的平方:

>>> [x * x for x in range(1, 11) if x % 2 == 0][4, 16, 36, 64, 100]
def f(n):    return n*n*na=list(f(x) for x in range(10) if x%2==0)print(a)

結果:

[0, 8, 64, 216, 512]

還可以使用兩層迴圈,可以產生全排列:

>>> [m + n for m in ‘ABC‘ for n in ‘XYZ‘][‘AX‘, ‘AY‘, ‘AZ‘, ‘BX‘, ‘BY‘, ‘BZ‘, ‘CX‘, ‘CY‘, ‘CZ‘]

三層和三層以上的迴圈就很少用到了。

運用列表產生式,可以寫出非常簡潔的代碼。例如,列出目前的目錄下的所有檔案和目錄名,可以通過一行代碼實現:

>>> import os # 匯入os模組,模組的概念後面講到>>> [d for d in os.listdir(‘.‘)] # os.listdir可以列出檔案和目錄[‘.emacs.d‘, ‘.ssh‘, ‘.Trash‘, ‘Adlm‘, ‘Applications‘, ‘Desktop‘, ‘Documents‘, ‘Downloads‘, ‘Library‘, ‘Movies‘, ‘Music‘, ‘Pictures‘, ‘Public‘, ‘VirtualBox VMs‘, ‘Workspace‘, ‘XCode‘]

for迴圈其實可以同時使用兩個甚至多個變數,比如dictitems()可以同時迭代key和value:

>>> d = {‘x‘: ‘A‘, ‘y‘: ‘B‘, ‘z‘: ‘C‘ }>>> for k, v in d.items():...     print(k, ‘=‘, v)...y = Bx = Az = C

因此,列表產生式也可以使用兩個變數來產生list:

>>> d = {‘x‘: ‘A‘, ‘y‘: ‘B‘, ‘z‘: ‘C‘ }>>> [k + ‘=‘ + v for k, v in d.items()][‘y=B‘, ‘x=A‘, ‘z=C‘]

最後把一個list中所有的字串變成小寫:

>>> L = [‘Hello‘, ‘World‘, ‘IBM‘, ‘Apple‘]>>> [s.lower() for s in L][‘hello‘, ‘world‘, ‘ibm‘, ‘apple‘]

練習:

如果list中既包含字串,又包含整數,由於非字串類型沒有lower()方法。用列表產生式,只保留字元串類型資料,並使其小寫 [‘Hello‘, ‘World‘, 18, ‘Apple‘, None] 

>>> L = [‘Hello‘, ‘World‘, 18, ‘Apple‘, None]>>> [s.lower() for s in L]Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<stdin>", line 1, in <listcomp>AttributeError: ‘int‘ object has no attribute ‘lower‘

使用內建的isinstance函數可以判斷一個變數是不是字串:

>>> x = ‘abc‘>>> y = 123>>> isinstance(x, str)True>>> isinstance(y, str)False

使用列表產生式,通過添加if語句保證列表產生式能正確地執行:

# -*- coding: utf-8 -*-L1 = [‘Hello‘, ‘World‘, 18, ‘Apple‘, None]# def low_str(s):#     if isinstance(s,str):#         return s.lower() #     else:#         return s       L2 = [x.lower()  for x in L1 if isinstance(x,str)]# 測試:print(L2)if L2 == [‘hello‘, ‘world‘, ‘apple‘]:    print(‘測試通過!‘)else:    print(‘測試失敗!‘)

結果:

[‘hello‘, ‘world‘, ‘apple‘]測試通過!
# -*- coding: utf-8 -*-L1 = [‘Hello‘, ‘World‘, 18, ‘Apple‘, None]def low_str(s):    if isinstance(s,str):        return s.lower()     else:        return s       L2 = [low_str(x)  for x in L1 ]# 測試:print(L2)

結果:

[‘hello‘, ‘world‘, 18, ‘apple‘, None]

 

python入門第十六天__列表產生式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.