对迭代器的延迟计算修改链接在一起
iterator-chain的Python项目详细描述
迭代器链
链接在一起,懒洋洋地计算对迭代器的修改。
安装
在requirements.txt
文件中包含iterator-chain
和/或使用pip
安装它。
$ pip install iterator-chain
API
从导入包开始。
importiterator_chain
启动链条
要启动链,请使用from_iterable
函数。它需要一个iterable。
an_iterable=[5,78,12,26]iterator_chain.from_iterable(an_iterable)
Function | Arguments | Description |
---|---|---|
^{ | • ^{ | Starts the iterator chain with the supplied iterable. Chaining and terminating methods can now be called on the result. |
继续链条
从那里,可以调用大量额外的方法来修改最初传入的iterable。方法是 概述如下。这些方法分为两类:链接或终止。
- 链接方法对迭代器中的元素应用一些修改,但保持链的活动性。 这允许随后对结果调用其他链接方法。 由于修改是惰性计算的,因此在终止方法之后的之前,不会应用链接方法中的任何修改。 打电话。
- 终止方法还对迭代器中的元素应用某些修改、请求某些信息或执行某些操作。他们返回来阻止锁链 实际值。此值将取决于首先执行的所有先前链接方法。
链接方法
Method | Arguments | Description |
---|---|---|
^{ | • ^{ | Will run the ^{ |
^{ | • ^{ | Will run the ^{ |
^{ | • ^{ | The ^{ |
^{ | Any duplicates will be removed. | |
^{ | • ^{ | The iterator will stop after ^{ |
^{ | Any element that is an iterable itself will have its elements iterated over first before continuing with the remaining elements. Strings (^{ | |
^{ | • ^{ • ^{ • ^{ | Sorts the iterator based on the elements' values. Use ^{ |
^{ | Reverses the iterator. The last time will be first, and the first item will be last. This method is expensive because it must serialize all the values into a list. |
终止方法
Method | Arguments | Description |
---|---|---|
^{ | Serializes the iterator chain into a ^{ | |
^{ | Returns the number of elements in the iterator | |
^{ | • ^{ | Returns just the first item in the iterator. If the iterator is empty, the ^{ |
^{ | • ^{ | Returns just the last item in the iterator. If the iterator is empty, the ^{ |
^{ | • ^{ | Returns the largest valued element in the iterator. If the iterator is empty, the ^{ |
^{ | • ^{ | Returns the smallest valued element in the iterator. If the iterator is empty, the ^{ |
^{ | • ^{ | Sums all the elements in the iterator together. If any of the elements are un-summable, the ^{ |
^{ | • ^{ | Applies the function to two elements in the iterator cumulatively. Subsequent calls to ^{ |
^{ | • ^{ | Executes ^{ |
^{ | • ^{ | Returns ^{ |
^{ | • ^{ | Returns ^{ |
^{ | • ^{ | Returns ^{ |
示例
importiterator_chainan_iterable=[5,78,12,26]iterator_chain.from_iterable(an_iterable) \ #starts the chain.map(lambdaelement:element*2) \ #multiplies every element by two: [10, 156, 24, 52].filter(lambdaelement:element>32) \ #keeps any element greater than 32: [156, 52].map(lambdaelement:element/3) \ #divides every element by three: [52.0, 17.333333333333332].list()#and finally returns a list of the result for later use in your application: [52.0, 17.333333333333332]