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)
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.
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.
Python doesn't have any support for cloning generators.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With