1 python pipe包管道包学习
参考: https://github.com/JulienPalard/Pipe
from pipe import *
[1, 2, 3, 4, 5] | tee | as_list
1
2
3
4
5
Out[32]: [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6] | as_list
Out[34]: [1, 2, 3, 4, 5, 6]
[1, 2, 3] | reverse | concat
Out[52]: '3, 2, 1'
[1,2,3,2,1] | index(value=2,start=2,stop=4)
Out[53]: 3
[1,2,3,2,1] | index(3)
Out[54]: 2
2 构造你自己的pipe管道函数
stdout = Pipe(lambda x: sys.stdout.write(str(x)))
select = Pipe(lambda iterable, pred: (pred(x) for x in iterable))
@Pipe
def stdout(x):
sys.stdout.write(str(x))
3 删除重复值
[1,1,2,2,3,3,1,2,3] | dedup |as_list
Out[50]: [1, 2, 3]
[1,1,2,2,3,3,1,2,3] | uniq | as_list
Out[51]: [1, 2, 3, 1, 2, 3]
4 groupby() 对列表实现分组计算
(1, 2, 3, 4, 5, 6, 7, 8, 9) | groupby(lambda x: x % 2 and "Even" or "Odd") | select(lambda x: "%s : %s" % (x[0], (x[1] | concat(', ')))) | concat(' / ')
Out[46]: 'Even : 1, 3, 5, 7, 9 / Odd : 2, 4, 6, 8'
[5, -4, 3, -2, 1] | sort(key=abs) | concat
Out[49]: '1, -2, 3, -4, 5'
5 求和和平均数
[1,2,3] | add
Out[17]: 6
[1, 2, 3] | select(lambda x: x * x) |average
Out[30]: 4.666666666666667
[1, 2, 3, 4, 5, 6] | average
Out[35]: 3.5
6 select函数,相当于map映射操作
[1,3,5] | select(lambda x:float(x +1)) |as_list
Out[20]: [2.0, 4.0, 6.0]
7 聚合函数
(1, 2, 3, 4, 5, 6, 7, 8, 9) | aggregate(lambda x, y: x + y)
Out[21]: 45
8 筛选和过滤
[1, 2, 3] | where(lambda x: x % 2 == 0) | as_list
Out[24]: [2]
[1, 2, 3, 4] | take_while(lambda x: x < 3) | concat
Out[25]: '1, 2'
[1, 2, 3, 4] | where(lambda x: x < 3) | concat
Out[26]: '1, 2'
9 take前几个元素和count生成器的长度
[1,2,3]|take(2) |as_list |where(lambda x : x ==2) |as_list |count
Out[27]: 1
[1,2,3]|count
Out[28]: 3
10 flatmap操作
[[1, 2], [3, 4], [5]] | chain |as_list
Out[31]: [1, 2, 3, 4, 5]
11 两个列表实现zip函数
(1, 2, 3, 4, 5, 6, 7, 8, 9) | izip([9, 8, 7, 6, 5, 4, 3, 2, 1]) | concat
Out[38]: '(1, 9), (2, 8), (3, 7), (4, 6), (5, 5), (6, 4), (7, 3), (8, 2), (9, 1)'
12 指定函数排序并选出max
('aa', 'b', 'fosdfdfo', 'qwerty', 'bar', 'zoog') | max(key=len)
Out[43]: 'fosdfdfo'
('aa', 'b', 'foo', 'qwerty', 'bar', 'zoog') | max()
Out[44]: 'zoog'
('aa', 'b', 'foo', 'qwerty', 'bar', 'zoog') | max
Out[45]: 'zoog'
13 索引截取数组元素
(1, 2, 3, 4, 5, 6, 7, 8, 9) | islice(2, 8) | concat
Out[36]: '3, 4, 5, 6, 7, 8'
(1, 2, 3, 4, 5, 6, 7, 8, 9) | islice(0,1) |as_list
Out[37]: [1]
14 any()和all()实现
(1, 3, 5, 6, 7) | any(lambda x: x >= 7)
Out[39]: True
(1, 3, 5, 6, 7) | any(lambda x: x > 7)
Out[40]: False
(1, 3, 5, 6, 7) | all(lambda x: x < 7)
Out[41]: False
(1, 3, 5, 6, 7) | all(lambda x: x <= 7)
Out[42]: True