23

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)

Community
  • 1
  • 1
Richard Rublev
  • 7,718
  • 16
  • 77
  • 121
  • Please explain exactly what you are trying to do. Because what you just got is a [generator](https://www.python.org/dev/peps/pep-0289/) and there is nothing *really* wrong. If you iterate over it you will get your output. But there are differences you need to be aware of. Make sure you read the link I provided. – idjaw Mar 14 '16 at 19:24

2 Answers2

42

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
Julien Spronck
  • 15,069
  • 4
  • 47
  • 55
4

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.

Mats Kindahl
  • 1,863
  • 14
  • 25