python中的列表推導淺析

來源:互聯網
上載者:User
列表推導(List comprehension)的作用是為了更方便地產生列表(list)。

比如,一個list變數的元素均為數字,如果需要將每個元素的值乘以2並產生另外一個list,下面是一種做法:
複製代碼 代碼如下:


#-*-encoding:utf-8-*-

list1 = [1,2,4,5,12]
list2 = []
for item in list1:
list2.append(item*2)
print list2


如果使用列表推導,可以這樣:
複製代碼 代碼如下:


#-*-encoding:utf-8-*-

list1 = [1,2,4,5,12]
list2 = [item*2 for item in list1 ]
print list2


可以通過if過濾掉不想要的元素,例如提取出list1中小於10的元素:
複製代碼 代碼如下:


#-*-encoding:utf-8-*-

list1 = [1,2,4,5,12]
list2 = [item for item in list1 if item < 10 ]
print list2


如果要將兩個list中的元素進行組合,可以:
複製代碼 代碼如下:


#-*-encoding:utf-8-*-

list1 = [1,2,3]
list2 = [4,5,6]
list3 = [(item1,item2) for item1 in list1 for item2 in list2 ]
print list3


官方文檔中給出了一個比較複雜的轉置矩陣的例子:
複製代碼 代碼如下:


#-*-encoding:utf-8-*-

matrix1 = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
]
matrix2 = [[row[i] for row in matrix1] for i in range(4)]
for row in matrix2:
print row


運行結果如下:
複製代碼 代碼如下:


[1, 5, 9]
[2, 6, 10]
[3, 7, 11]
[4, 8, 12]
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.