刚开始接触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来类比说明我很能接受。谢谢!