[問題] 請問pipe operator以及vectorization

看板Python作者 (missing)時間6年前 (2018/05/24 10:49), 6年前編輯推噓3(307)
留言10則, 4人參與, 6年前最新討論串1/1
剛開始接觸Python幾個月,有兩個問題想要請教: 1. Python有大家比較常用的pipe operator嗎? 例如shell有`|`; R透過套件可以有`%>%`(類似shell的`|`)、 甚至`%<>%`(把後方執行的結果再assign回去,像是Python的`+=`的萬用版)。 我對這種寫法已經有點習慣, 想請問在Python實現的方式是? 我搜尋了一下SO,有發現幾篇,但大家寫的都不一樣: - https://stackoverflow.com/q/5988665/6666231 - https://stackoverflow.com/q/28252585/6666231 請問大家,有比較常用或推薦的嗎? 2. Python的vectorization要怎麼實現? ```r strings <- c("dogs", "cats", "doggies", "I have a dog") mask <- grepl("^dog", strings) mask # TRUE FALSE TRUE FALSE strings[mask] # "dogs" "doggies" ``` 上面的意思是: 在"dogs"、"cats"、"doggies"、"I have a dog"中找"dog"開頭的字串, 並且回傳是否存在的邏輯值,存成物件`mask`。 `string[mask]`則是直接用邏輯值回傳符合條件的元素。 由於R語言的特性是內建vectorization的概念, 到了Python好像每件事都變得棘手: ```python import re strings = ["dogs", "cats", "doggies", "I have a dog"] mask = list(map(lambda string: True if re.match("dog", string) else False, strings)) mask # [True, False, True, False] strings[mask] # TypeError: list indices must be integers or slices, not list ``` 產生`mask`時變成我要自建一個function再`map`它, 雖然只是`lambda`但還是覺得多了一步, 想請問有沒有別的方法? 接下來`strings[mask]`更是直接爆炸 囧... 我看了一下itertools,但好像不是用在這種地方? 請問Python內上述的vectorization要怎麼實現呢? PS: 我自認對R滿熟悉的,所以如果用R來類比說明我很能接受。謝謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 203.74.120.191 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1527130178.A.0B7.html

05/24 10:58, 6年前 , 1F
將map換成filter, 出來的就會直接是你要的.
05/24 10:58, 1F
※ 編輯: clsmbstu (203.74.120.191), 05/24/2018 11:38:53

05/24 11:59, 6年前 , 2F
Thanks!! 多學到一招~
05/24 11:59, 2F

05/24 12:17, 6年前 , 3F
list comprehensions 或一些函數式程式相關函式
05/24 12:17, 3F

05/24 12:17, 6年前 , 4F
要 vector 通常是用 NumPy 為基礎的套件
05/24 12:17, 4F

05/24 14:12, 6年前 , 5F
functional programming的做法在Python裡面比較不常用
05/24 14:12, 5F

05/24 14:12, 6年前 , 6F
通常會用list comprehension而不用map和filter
05/24 14:12, 6F

05/24 14:12, 6年前 , 7F
pipe的本質就是一個接受一個參數的函式
05/24 14:12, 7F

05/24 14:12, 6年前 , 8F
我Python很熟很不能接受R這個語言(非常不適應...
05/24 14:12, 8F

05/24 14:12, 6年前 , 9F
同樣我想用R的思維很難把Python寫好
05/24 14:12, 9F

05/24 18:25, 6年前 , 10F
我知道了 感謝樓上兩位!
05/24 18:25, 10F
文章代碼(AID): #1R1YX22t (Python)