Say I have a list
data = [] data.append("A") data.append("B") data.append("C") data.append("D")
How do I convert this to a generator? Any help with sample code would be highly appreciated...
Found a URL: http://eli.thegreenplace.net/2012/04/05/implementing-a-generatoryield-in-a-python-c-extension/
Is this what I want to do?
Use the __iter__() and __next__() Method to Convert Object to Iterator in Python. As the name suggests, an iterator returns the data values one by one. The iterator object does this with the help of the __iter__() and the __next__() method. The __iter__() and __next__() method together form the iterator protocol.
To make an array iterable either you need to convert it to a stream or as a list using the asList() or stream() methods respectively. Then you can get an iterator for these objects using the iterator() method.
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
Are you sure, you want to create a generator? A generator is function which returns an iterator type, constructed e.g. by using the yield
keyword (cf. term-generator). If you really want this, steven-rumbalski's answer is precisely what you are looking for:
data_gen = (y for y in data)
Most of the time, you will want to directly create an iterator object, e.g. to use the next()
method. In this case, the answer is implicit in the comment by mgilson above:
data_iter = iter(data)
which is equivalent to data_iter = data.__iter__()
, cf. functions#iter.
>>> (n for n in [1, 2, 3, 5]) <generator object <genexpr> at 0x02A52940>
works in Python 2.7.4+
>>> a2g = lambda x : (n for n in x) >>> a2g([1, 2, 3, 4, 5]) <generator object <genexpr> at 0x02A57CD8>
Edit:
One more slight variation of a lambda generator factory pattern
>>> a2g = lambda *args: (n for n in args) >>> for i in a2g(1, 2, 3, 4, 5): print i 1 2 3 4 5
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