简体   繁体   English

返回由生成器或迭代器生成的所有元素的标准方法

[英]Standard method for returning all elements generated by a generator or iterator

I'm looking for a neat, ideally standard-library-based method or recipe for turning an iterator or generator object into a list containing all the elements that you would get if you iterated over this object. 我正在寻找一种整洁的,理想的基于标准库的方法或方法,用于将迭代器或生成器对象转换成包含所有元素的列表,这些元素将在您对该对象进行迭代时得到。 If there are any different solutions regarding Python 2.7 or 3.x I'd also be interested in knowing. 如果有关于Python 2.7或3.x的任何其他解决方案,我也想知道。 Basically, I'm looking for something functionally equivalent to: 基本上,我正在寻找功能上等效的东西:

def expand(obj):
    result = []
    for o in obj:
        result.append(o)
    return result

I understand that generators and iterators in Python come with lots of benefits, and that this probably shouldn't be used in .py files. 我知道Python中的生成器和迭代器具有很多优点,并且可能不应该在.py文件中使用它。 However, I do think this has its uses, especially when programming interactively and when using small datasets for testing. 但是,我确实认为这有其用途,尤其是在进行交互编程以及使用小型数据集进行测试时。

My best answer so far is list comprehension: 到目前为止,我最好的答案是列表理解:

In [55]: a=[1,2,3]
In [56]: r=reversed(a)
In [57]: r
Out[57]: <listreverseiterator at 0x101f51a10>

In [58]: [x for x in r]
Out[58]: [3, 2, 1]

In [59]: def f(x):
   ....:     while x > 0:
   ....:         x-=1
   ....:         yield x
   ....:         

In [60]: [x for x in f(4)]
Out[60]: [3, 2, 1, 0]

I've tried searching Google and StackOverflow without finding anything obvious, and I've checked the itertools and functools docs - most of my attempts based on those just result in more objects. 我尝试搜索Google和StackOverflow时没有发现任何明显的问题,并且检查了itertoolsfunctools文档-我基于这些尝试的大部分尝试都导致了更多对象。 I also had a quick look at IPython magicks , but didn't notice anything obvious there. 我也快速浏览了IPython magicks ,但没有发现任何明显的地方。

有一个非常简单的解决方案: list(the_iterator)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM