如何在Python中创建迭代器管道? [英] How to create an iterator pipeline in Python?
问题描述
是否有用于在Python中创建迭代器管道的库或推荐方法?
Is there a library or recommended way for creating an iterator pipeline in Python?
例如:
>>>all_items().get("created_by").location().surrounding_cities()
我还希望能够访问迭代器中对象的属性。在上面的示例中, all_items()
返回项的迭代器,并且项具有不同的创建者。
I also want to be able to access attributes of the objects in the iterators. In the above example, all_items()
returns an iterator of items, and the items have different creators.
.get(created_by)
然后返回项目的created_by属性(这是人物),然后 location()
返回每个人的城市,然后将其传送到 surrounding_cities()
,其中返回每个位置的周围城市的所有迭代器(因此最终结果是周围城市的大型列表)。
The .get("created_by")
then returns the "created_by" attribute of the items (which are people), and then location()
returns the city of each person, and then pipes it to surrounding_cities()
, which returns all an iterator of the surrounding cities for each location (so the end result is a large list of surrounding cities).
推荐答案
你不只是在处理迭代器吗?在Python中使用迭代器的自然方法是for循环:
Aren't you just processing an iterator? The natural way to use an iterator in Python is the for loop:
for item in all_items():
item.get("created_by").location().surrounding_cities()
还有其他可能性如根据你正在做的事情可能更有意义的列表理解(如果你试图生成一个列表作为你的输出,通常会更有意义。)
There are other possibilities such as list comprehensions which may make more sense depending upon what you're doing (usually makes more sense if you're trying to generate a list as your output).
这篇关于如何在Python中创建迭代器管道?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!