开发者

Is it possible to convert a list-type into a generator without iterating through?

开发者 https://www.devze.com 2023-03-04 23:52 出处:网络
I know that it\'s possible to convert generators into lists at a \"low-level\" (eg. list(i for i in xrange(10))), but is it possible to do the reverse without iterating through the list fi开发者_C百科

I know that it's possible to convert generators into lists at a "low-level" (eg. list(i for i in xrange(10))), but is it possible to do the reverse without iterating through the list fi开发者_C百科rst (eg. (i for i in range(10)))?

Edit: removed the word cast for clarity in what I'm trying to achieve.

Edit 2: Actually, I think I may have misunderstood generators at a fundamental level. That'll teach me to not post SO questions before my morning coffee!


Try this: an_iterator = iter(a_list) ... docs here. Is that what you want?


You can take a list out of an iterator by using the built-in function list(...) and an iterator out of a list by using iter(...):

mylist = list(myiterator)
myiterator = iter(mylist)

Indeed, your syntax is an iterator:

iter_10 = (i for i in range(10))

instead of using [...] which gives a list.

Have a look at this answer Hidden features of Python


Indeed it's possible a list possesses the iterator interface:

list_iter = list.__iter__() # or iter(list), returns list iterator
list_iter.__next__() # list_iter.next() for python 2.x

So,

lst_iter = iter(lst)

does the trick.

Though it makes more sense to use comprehensions and make a generator out of it: e.g.

lst_iter_gt_10 = (item for item in lst if item > 10)


I'm not sure you mean, but what you typed is valid Python code:

>>> x = (i for i in range(10))
>>> x
<generator object at 0xb7f05f6c>
>>> for i in x: print i
0
1
2
3
4
5
6
7
8
9


next was key:

next(iter([]), None)

where you can replace None with whatever default you want

0

精彩评论

暂无评论...
验证码 换一张
取 消