toolz, python函数式库事实标准

2022-05-11  本文已影响0人  深圳都这么冷

toolz 是什么

操作迭代器,函数和字典的函数集合
简而言之,toolz是python事实上的函数式标准库

主要特性:

安装

pip install toolz

API组成

itertoolz操作可迭代对象,如: groupby, unique, interpose
functoolz操作高阶函数,如: memoize, curry, compose
dicttoolz操作字典结构,如: assoc, update-in, merge

例子

>>> def stem(word):
...     """ Stem word to primitive form """
...     return word.lower().rstrip(",.!:;'-\"").lstrip("'\"")

>>> from toolz import compose, frequencies
>>> from toolz.curried import map
>>> wordcount = compose(frequencies, map(stem), str.split)

>>> sentence = "This cat jumped over this other cat!"
>>> wordcount(sentence)
{'this': 2, 'cat': 2, 'jumped': 1, 'over': 1, 'other': 1}

总结

toolz是一个非常强大的函数库,可以帮助你写出短小易读,优雅强大的代码。
更多功能参见官方文档PyToolz API Documentation

上一篇下一篇

猜你喜欢

热点阅读