一些迭代器实用程序
dm.iter的Python项目详细描述
迭代器实用程序的一个小集合。
目前,有一个与关系相关的单一效用族。
关系实用程序
这些实用程序在dm.iter.relation中实现。
关系由元素到 其直接相关元素的迭代器。 映射或者是具有__getitem__方法的对象, 未定义的可调用的引发ValueError。 输入参数或支持订阅的对象。 必须允许元素作为集合元素。
可用的实用程序有depth_first_search和breath_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)