之前就看到python的一个比较有趣的包,今天来学习一下。
python Pipe包可以实现管道操作命令,类似于linux,可以实现高效的代码写作,pipe使用'|'传递数据流,并且定义了一系列的“流处理”函数用于接受并处理数据流,并最终再次输出数据流或者是将数据流归纳得到一个结果。
因为pipe包不是python内置的库,所以要自己手动下载下来,下载网址:https://pypi.org/project/pipe/#files,一开始我是下载了0.4.9版本的,一直安装不了,后来下了这个1.6.0安装就成功了,不过在windows上安装0.4.9的版本是可以的。
下面是一些例子:
#(1)加法运算
from pipe import * #直接import pipe是不行的
range(5) | add #使用add求和
#(2) 条件过滤
#求偶数和需要使用到where,作用类似于内建函数filter,过滤出符合条件的元素:
range(5) | where(lambda x: x % 2 == 0) | add
#(3)需要对元素应用某个函数可以使用select,作用类似于内建函数map;需要得到一个列表,可以使用as_list:
[1,2,3] | select(lambda x:x**2) | as_list
#result
[1, 4, 9]
#筛选和过滤
[1, 2, 3, 4] | take_while(lambda x: x < 3) | concat
[1, 2, 3, 4] | where(lambda x: x < 3) | concat
#结果:'1, 2'
[1, 2, 3, 4] | concat("#") #concat连接
#结果:'1#2#3#4'
#take :提取前几个元素,count:返回生成器的长度
[1,2,3] | take(2) | as_list | where(lambda x : x ==2) | as_list | count
[1,2,3]|count
#any(),只要存在一个就返回true
(1, 3, 5, 6, 7) | any(lambda x: x >= 7) #结果:Ture
(1, 3, 5, 6, 7) | any(lambda x: x > 7) #结果:Flase
#all(),必须全部满足才会返回true
(1, 3, 5, 6, 7) | all(lambda x: x < 7)
(1, 3, 5, 6, 7) | all(lambda x: x <= 7)
#max() 按照key中的指定的函数来排序,然后筛选出max的函数
('aa', 'b', 'fosdfdfo', 'qwerty', 'bar', 'zoog') | max(key=len)
('aa', 'b', 'foo', 'qwerty', 'bar', 'zoog') | max() #不填key的时候返回的是 'zoog',应该是默认按位置排序
#平均数
[1, 2, 3, 4, 5, 6] | average
#封装itertools.chain
[[1, 2], [3, 4], [5]] | chain | concat
(1, 2, 3) | chain_with([4, 5], [6]) | concat
自定义函数
pipe中还包括了更多的流处理函数。你甚至可以自己定义流处理函数,只需要定义一个生成器函数并加上修饰器Pipe。如下定义了一个获取元素直到索引不符合条件的流处理函数:
@Pipe
def take_x(iterable, predicate):
for idx, x in enumerate(iterable):
if predicate(idx): yield x
else: return
#应用
[1,1,2,3,5,8,13,21,34]| take_while_idx(lambda x: x < 6) | as_list
#结果:[1, 1, 2, 3, 5, 8]
#自己写了一个比较简单的
@Pipe
def add_ele(iterable,qte):
for i in iterable:
i=i+qte
yield i
#运用
[1,2,3] | add_ele(3) | as_list
#结果:[4, 5, 6]
———————————————————————————————————————————————
filter函数小知识 :
filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。
语法:filter(function, iterable),function为过滤函数,iterable为迭代对象
例:过滤列表中的奇数
def is_odd(n):
return n % 2 == 1
#% 是python 运算符 返回余数
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)
#result
#[1, 3, 5, 7, 9]
#这里的函数def也可以直接用lambda,可以让代码更简洁
newlist=filter(lambda x: x % 2 == 1 , [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
map()函数小知识
map() 会根据提供的函数对指定序列做映射,语法:map(function, iterable, ...)
例:
def square(x) : # 计算平方数
return x ** 2
map(square, [1,2,3,4,5]) # 计算列表各个元素的平方
#result
#[1, 4, 9, 16, 25]
#下面用lambda匿名函数
map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # 使用 lambda 匿名函数
# 提供了两个列表,对相同位置的列表数据进行相加
map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
#result
#[3, 7, 11, 15, 19]
itertools.chain
对多个对象执行相同的操作且这几个对象在不同的容器中,这时候就用到了itertools.chain的函数
from itertools import chain
a = [1,2,3,4]
b = [5,6,7,8]
for v in chain(a,b):
print(v*5)
#result
5
10
15
20
25
30
35
40











网友评论