如何在Python中创建一个迭代器管道?

4
有没有在Python中创建迭代器流的库或推荐方法?
例如:
>>>all_items().get("created_by").location().surrounding_cities()

我还希望能够访问迭代器中对象的属性。在上面的例子中,all_items()返回一个物品的迭代器,而这些物品由不同的创建者创建。

然后,.get("created_by")返回物品(即人)的“created_by”属性,接着location()返回每个人所在城市,并将其传输到surrounding_cities(),该函数返回每个位置周围城市的迭代器(因此最终结果是一个大型周围城市列表)。


1
你要找的是:http://code.google.com/p/python-pipeline/ - janislaw
我正在尝试了解如何在Python中模拟Gremlin:http://www.youtube.com/watch?v=5wpTtEBK4-E - espeed
3个回答

4

你只是在处理一个迭代器吗?在Python中使用迭代器的自然方式是使用for循环:

for item in all_items():
    item.get("created_by").location().surrounding_cities()

还有其他可能性,比如列表推导式,根据你所做的事情可能更加合理(如果你试图生成一个列表作为输出,通常是更合理的选择)。


1

我建议您查找如何使用Python中的协程实现管道,更具体地说是这个管道示例

如果按照上述示例实现您的函数,则代码可能如下所示(为了简单起见,我假设您希望打印这些城市):

all_items(get_location(get_creators(get_surrounding_cities(printer()))))

为什么不使用 all_items(get_creators(get_location(get_surrounding_cities(printer())))) 呢?all_itemsget_creators 表现不同于 get_locationget_surrounding_cities,这是有原因的吗? - slowdog
其实你是对的,没必要表现得不同,我编辑了我的回答。 - bpgergo

1
在您的示例中,您实际上只有两种迭代器方法:all_itemssurrounding_cities,因此您可以使用itertools.chain来做得相当不错:
from itertools import chain

cities = chain.from_iterable(
    item.get("created_by").location().surrounding_cities() for item in all_items()
)
cities将是一个迭代器,列出所有项目周围的城市。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接