Skip to main content

一些富迭代器概念的实现

项目描述

# iter2

这个库提供了
[rich-iterator](http://code.activestate.com/recipes/498272-rich-iterator-wrapper/)
概念的实现,灵感来自
[Rust 的 std::iter::Iterator](https ://doc.rust-lang.org/std/iter/trait.Iterator.html),
[Java 的 Stream](https://docs.oracle.com/javase/8/docs/api/?java/util/ stream/Stream.html)
和 [more-itertools 库](https://more-itertools.readthedocs.io/en/latest/)。


## 用法
库的主要对象是`iter2`。它的行为类似于内置的
“iter”,只是它创建了一个富迭代器的实例。
```python
iter2(['dzen', 'of', 'python']).map(str.capitalize).join(' ') # 'Dzen Of Python'
```

> **every** 的rich-iterator 方法返回新的迭代器使原来的rich-iterator **无效**,所以它
> **不能在任何迭代过程中使用**。可以使用 `ref` 方法绕过此行为。

可以使用 `raw` 方法检索原始迭代器:
```python
orig = iter2.range(5).raw()
tuple(orig) # (0, 1, 2, 3, 4)
``

`iter2` has一些构建值序列的方法:
```python
iter2.of('a', 'b', 'cde').join() # 'abcde'
iter2.range(5).map(str).join( ) # '01234'
iter2.count_from(100).take(5).map(str).join('->') # '100->101->102->103->104'
iter2.numeric_range(1.0 , 3.5, 0.3).to_tuple() # (1.0, 1.3, 1.6, 1.9, 2.2, 2.5, 2.8, 3.

```

和多个迭代的一些算法方法:
```python
iter2.cartesian_product(range(2), repeat=2).to_tuple() # ((0, 0), (0, 1), (1, 0), (1, 1))
iter2.zip_longest(range(3), range(1, 5), fillvalue=-1).to_tuple() # ((0, 1), (1, 2), (2 , 3), (-1, 4))
iter2.chain(['Somewhere', 'over'], ['the', 'Rainbow']).join(' ') # 'Somewhere over the Rainbow
# and some其他 ...
```


### 比较
下面是一些与基于内置和基于 itertools 的
实现相比的用法示例:

```python
from itertools import islice
from functools import reduce
import operator

from iter2 import iter2

square = lambda x : x ** 2
奇数 = lambda x: x % 2 == 1

def fibonacci():
a = b = 1
while True:
yield a
a, b = b, a + b


# 示例 1:
cool_song = 'Somewhere over the Rainbow'
# "from `cool_song` 接受大写字符并用 '+' 连接它们"
iter2(cool_song).filter(str.isupper).join('+')
# vs
# "with '+' 连接来自 `cool_song` 的大写字符"
'+ '.join(filter(str.isupper, cool_song))


# 示例 2:
# “对于 0..99 中的值,取奇数的平方并将它们相加”(听起来像算法)
iter2.range(100).map (square).filter(odd).sum()
# vs
# "将奇数的值求和,它们是 0 中值的平方。99"(听起来像狗屎)
sum(filter(odd, map(square, range(100))))
# "0..99 中奇数值的平方和"
sum(x ** 2 for x in range(100) if x % 2 = = 1) # 幸运的是,平方不会改变奇数


# 示例 3:“玩无限序列”
(iter2(fibonacci())
.drop(10)
.filter(odd)
.map(square)
.take(5)
.product()) # `.fold(operator.mul)` 的快捷方式
# vs
reduce(operator.mul,islice(map(square, filter(odd, islice(fibonacci(), 10, None))), 5) ) # (计算大括号平衡和逗号位置)
# (为了更清楚):
reduce(
operator.mul,
islice(
map(
square,
filter(
奇数,
islice(fibonacci(), 10, None)
)
),
5
)
) # 还是不?
```

##Changelog

####v1.1

- 元组方法

#### v1.0

- 初始


项目详情


下载文件

下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。

源分布

iter2-1.1.tar.gz (19.6 kB 查看哈希

已上传 source

内置分布

iter2-1.1-py3-none-any.whl (26.8 kB 查看哈希

已上传 py3