Python 如何将生成器对象转换为列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35996253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert generator object into list?
提问by Richard Rublev
My code
我的代码
def yieldlines(thefile, whatlines):
return (x for i, x in enumerate(thefile) if i in whatlines)
file1=open('/home/milenko/EDIs/site1/newst2.txt','r')
whatlines1 = [line.strip() for line in open('m1.dat', 'r')]
x1=yieldlines(file1, whatlines1)
print x1
I got
我有
<generator object <genexpr> at 0x7fa3cd3d59b0>
Where should I put the list,or I need to rewrite the code?
我应该把列表放在哪里,或者我需要重写代码?
I want my program to pen the file and read the content so for specific lines that are written in m1.dat.I have found that solution Reading specific lines only (Python)
我希望我的程序写入文件并读取 m1.dat 中写入的特定行的内容。我发现解决方案 仅读取特定行(Python)
回答by Julien Spronck
If you actually need a list, you can just do:
如果你真的需要一个列表,你可以这样做:
lst = list(generator_object)
However, if all you want is to iterate through the object, you do not need a list:
但是,如果您只想遍历对象,则不需要列表:
for item in generator_object:
# do something with item
For example,
例如,
sqr = (i**2 for i in xrange(10)) # <generator object <genexpr> at 0x1196acfa0>
list(sqr) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
sqr = (i**2 for i in xrange(10))
for x in sqr:
print x,
# 0 1 4 9 16 25 36 49 64 81
回答by Mats Kindahl
To convert a generator expression into a list it is sufficient to do:
要将生成器表达式转换为列表,只需执行以下操作:
list(<generator expression>)
Beware though if the generator expression can generate an infinite list, you will not get what you expect.
但请注意,如果生成器表达式可以生成无限列表,您将无法获得预期的结果。