一些迭代器实用程序

dm.iter的Python项目详细描述


迭代器实用程序的一个小集合。

目前,有一个与关系相关的单一效用族。

关系实用程序

这些实用程序在dm.iter.relation中实现。

关系由元素到 其直接相关元素的迭代器。 映射或者是具有__getitem__方法的对象, 未定义的可调用的引发ValueError。 输入参数或支持订阅的对象。 必须允许元素作为集合元素。

可用的实用程序有depth_first_searchbreath_first_search。 它们将关系和元素迭代器“根”作为参数 并为“根”生成关系的传递闭包 深度优先或呼吸优先。

让我们看一个小例子。我们的关系是 0和11作为域并将元素映射到该元素的三倍。

>>> def relation(x):
...   if not (isinstance(x, int) and 0 <= x < 11): raise ValueError
...   return (3 * x,)
...
>>> from dm.iter.relation import depth_first_search, breadth_first_search
>>> tuple(depth_first_search(relation, ()))
()
>>> tuple(breadth_first_search(relation, ()))
()
>>> tuple(depth_first_search(relation, (1, 2, 3)))
(1, 3, 9, 27, 2, 6, 18)
>>> tuple(breadth_first_search(relation, (1, 2, 3)))
(1, 2, 3, 6, 9, 18, 27)
>>> dfs = depth_first_search(relation, (1, 2, 3))
>>> dfs.next()
1
>>> dfs.next()
3

现在让我们的关系映射x(2*x, 3*x)

>>> def relation(x):
...   if not (isinstance(x, int) and 0 <= x < 11): raise ValueError
...   return (2 * x, 3 * x)
...
>>> tuple(depth_first_search(relation, (1,)))
(1, 2, 4, 8, 16, 24, 12, 6, 18, 3, 9, 27)
>>> tuple(breadth_first_search(relation, (1,)))
(1, 2, 3, 4, 6, 9, 8, 12, 18, 27, 16, 24)

关系也可以由字典指定。

>>> relation = dict((i, (2*i, 3*i)) for i in range(11))
>>> tuple(depth_first_search(relation, (1,)))
(1, 2, 4, 8, 16, 24, 12, 6, 18, 3, 9, 27)
>>> tuple(breadth_first_search(relation, (1,)))
(1, 2, 3, 4, 6, 9, 8, 12, 18, 27, 16, 24)

或者具有__getitem__方法的对象:

>>> from UserDict import UserDict
>>> relation = UserDict(relation)
>>> tuple(depth_first_search(relation, (1,)))
(1, 2, 4, 8, 16, 24, 12, 6, 18, 3, 9, 27)
>>> tuple(breadth_first_search(relation, (1,)))
(1, 2, 3, 4, 6, 9, 8, 12, 18, 27, 16, 24)

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java如何向xsi:nil元素添加另一个属性?   Java抽象泛型方法,使用具体类型实现通配符   java使用pcap4j截断pcap文件   当我放置字母a、b和c时,java中的异常预期会下降   java设置活动对话框不可取消   接口类型变量上的Java克隆   使用Java或BouncyCastle对CSR(证书签名请求)进行安全解码/读取   java调用SavingsAccount对象上的函数并打印结果   java如何在Android应用程序上显示地图上的兴趣点(POI)并与之交互?   如果在JavaFX中的ResultSet中未找到任何内容,则显示java警报   java我将springboot和@component与@scheduled一起使用,它每12小时锁定一次   ApachePOI如何使用java删除包含字符串的word表的行   java如果对象(x,y)靠近其他对象(x,y)   从未对JMSException调用java JMS CachingConnectionFactory OneException方法   javascript使用java将HTML页面转换为MS word