Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert generator object into list? [duplicate]

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)

like image 469
Richard Rublev Avatar asked Mar 14 '16 19:03

Richard Rublev


People also ask

How do I turn a generator object into a list?

Using the list() function to convert generator to list in Python. The list() constructor is used to initiate list objects. We can pass a generator object to this function to convert generator to list in Python.

How do you convert a generator to a string in Python?

The most Pythonic way to concatenate a list of objects is the expression ''. join(str(x) for x in lst) that converts each object to a string using the built-in str(...) function in a generator expression. You can concatenate the resulting list of strings using the join() method on the empty string as a delimiter.

Can you copy a generator Python?

Python doesn't have any support for cloning generators.


Video Answer


1 Answers

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
like image 184
Julien Spronck Avatar answered Oct 06 '22 01:10

Julien Spronck