[問題] 請問pipe operator以及vectorization
剛開始接觸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
05/24 10:58, 1F
※ 編輯: clsmbstu (203.74.120.191), 05/24/2018 11:38:53
→
05/24 11:59,
6年前
, 2F
05/24 11:59, 2F
推
05/24 12:17,
6年前
, 3F
05/24 12:17, 3F
→
05/24 12:17,
6年前
, 4F
05/24 12:17, 4F
推
05/24 14:12,
6年前
, 5F
05/24 14:12, 5F
→
05/24 14:12,
6年前
, 6F
05/24 14:12, 6F
→
05/24 14:12,
6年前
, 7F
05/24 14:12, 7F
→
05/24 14:12,
6年前
, 8F
05/24 14:12, 8F
→
05/24 14:12,
6年前
, 9F
05/24 14:12, 9F
→
05/24 18:25,
6年前
, 10F
05/24 18:25, 10F