Try   HackMD

List Comprehension

LHB阿好伯, 2020/12/21

tags: Python_30 R & python

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Python語法簡單易學且非常簡潔
今天要來學習的Comprehension即是Python的Pythonic語法之一
可以運用在任何可疊代的物件(Iterable Object)上
將前面學的Loops迴圈濃縮在一行程式碼即可完成多行的任務
讓我們的程式碼更簡潔增加可讀性

清單(List)的Comprehension

Loops迴圈中大大多數程式語言都可以使用for loops

# Python 語法 for 疊代器 in 可疊代的物件: 執行程式碼(須包含疊代器)

然而python的Comprehension可以進一步濃縮語法

# Python語法 [執行程式碼 for 疊代器 in 可疊代的物件 if 條件句]

簡單的我們先嘗試生成一個數列

# Python code numbers = [i for i in range(1, 11)] print(numbers)

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

計算數列1~10的平方

# Python code squares = [i * i for i in range(11)] print(squares)

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

結合if條件式

判斷數列中1~21那些是偶數

# Python code even_numbers = [i for i in range(1, 21) if i % 2 == 0] print(even_numbers)

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

或是判斷1~21中不是偶數的

# Python code odd_numbers = [i for i in range(1, 21) if i % 2 != 0] print(odd_numbers)

[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

多個判斷式也是沒問題

# Python code odd_numbers = [i for i in range(-21, 21) if i % 2 != 0 and i > 0] print(odd_numbers)

使用Comprehension還有其他優點
有更好的效率執行速度高於原本使用的for loop

使用time模組進行量測
速度快了近三倍

參考資料

import time arr1 = [] s = time.time() for i in range(int(1e+6)): arr1.append(i) print('took {} secs'.format(round(time.time() - s, 3))) s = time.time() arr2 = [i for i in range(int(1e+6))] print('took {} secs'.format(round(time.time() - s, 3)))

took 0.228 secs
took 0.082 secs

集合(Set)Comprehension的用法和串列(List)Comprehension幾乎一樣
不同的地方是集合(Set)使用大括弧符號{}
最後結果其中的元素並不會重覆

🌟全文可以至下方連結觀看或是補充
https://hackmd.io/@LHB-0222/30_Days_of_Python-13

全文分享至

https://www.facebook.com/LHB0222/

https://www.instagram.com/ahb0222/

有疑問想討論的都歡迎於下方留言

喜歡的幫我分享給所有的朋友 \o/

有所錯誤歡迎指教

全部文章列表

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →