是否有用于在 Python 中创建迭代器管道的库或推荐方法?
例如:
>>>all_items().get("created_by").location().surrounding_cities()
我还希望能够访问迭代器中对象的属性。在上面的例子中,all_items()
返回一个项目的迭代器,项目有不同的创建者。
然后 .get("created_by")
返回项目(人)的“created_by”属性,然后 location()
返回城市每个人,然后将其通过管道传递给 surrounding_cities()
,它返回每个位置周围城市的所有迭代器(因此最终结果是周围城市的大列表)。
最佳答案
你不只是处理一个迭代器吗?在 Python 中使用迭代器的自然方式是 for 循环:
for item in all_items():
item.get("created_by").location().surrounding_cities()
还有其他可能性,例如列表理解,这可能更有意义,具体取决于您在做什么(如果您尝试生成列表作为输出,通常更有意义)。
关于python - 如何在 Python 中创建迭代器管道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6188558/