Syntax for reusable iterable?

2024/10/8 0:33:41

When you use a generator comprehension, you can only use the iterable once. For example.

>>> g = (i for i in xrange(10))
>>> min(g)
0
>>> max(g)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
ValueError: max() arg is an empty sequence

Which is kind of annoying considering that works differently than list comprehensions.

You could do g = lambda (): (i for i in xrange(10)) to make it reusable, but then you have to do g () instead of g (EDIT: The problem with this isn't that g () is too long to type, but that if a function expects an iterable, you can't tell it to do g () instead of g.__iter__()). You could also do

class gObject(object):def __iter__(self): return (i for i in xrange(10))g = gObject()

but that is significantly longer than typing g = (i for i in xrange(10)). Is there a shorter syntax than gObject to accomplish this task?

Notes:

  • We may assume that the iterable will not consume elements from other permanent iterables. For example, if I did z = iter(xrange(10)), I would not try to define g = (i for i in z), since that could only work once (without cloning z).
  • g will no longer be an iterator. Rather, it will now be an iterable. I am fine with that. Indeed, that is kind of the point.
  • It should work for infinite iterables. For example, a list comprehension would not work since it only works in finite cases.
  • We may assume that any initialization costs are cheap, so rerunning the code defining g would not be an issue.
Answer

I don't fully follow the comments, but itertools.tee can give me multiple iterables:

In [518]: g1,g2,g3 = itertools.tee((i for i in range(10)), 3)
In [519]: min(g1), max(g2)
Out[519]: (0, 9)
In [520]: a = 0
In [521]: while a<10:...:     a += next(g3)      # simulate an infinite sequence...:     
In [522]: a
Out[522]: 10
In [523]: list(g3)
Out[523]: [5, 6, 7, 8, 9]

Or without unpacking:

def foo(g):a=0while a<12:a += next(g)return (a, list(g))In [525]: alist = itertools.tee((i for i in range(10)),3)...: flist = [min, max, foo]...: for f,a in zip(flist, alist):...:     print(f(a))
0
9
(15, [6, 7, 8, 9])

(This is using Py3)

https://en.xdnf.cn/q/118764.html

Related Q&A

Buildozer Problem. I try to make apk file for android, but i cant

artur@DESKTOP-SMKQONQ:~/Suka$ lsbuildozer.spec main.pyartur@DESKTOP-SMKQONQ:~/Suka$ buildozer android debugTraceback (most recent call last):File "/usr/local/bin/buildozer", line 10, in <…

how to run python script with ansible-playbook?

I want to print result in ansible-playbook but not working. python script: #!/usr/bin/python3import timewhile True:print("Im alive")time.sleep(5)deploy_python_script.yml:connection: localbeco…

How to concatenate pairs of row elements into a new column in a pandas dataframe?

I have this DataFrame where the columns are coordinates (e.g. x1,y1,x2,y2...). The coordinate columns start from the 8th column (the previous ones are irrelevant for the question) I have a larger exam…

Python: using threads to call subprocess.Popen multiple times

I have a service that is running (Twisted jsonrpc server). When I make a call to "run_procs" the service will look at a bunch of objects and inspect their timestamp property to see if they s…

Find a substring [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 5…

Image processing with single to multiple images

I have an Image showing below: I need to crop the order using python coding. What I need is only the card. So I want to crop the border. How to do it??This is the output I got using the code mentione…

SQLAlchemy Automap not loading table

I am using SQLAlchemy version 2.0.19 (latest public release). I am trying to map existing tables as documented in https://docs.sqlalchemy.org/en/20/orm/extensions/automap.html#basic-use I created a SQL…

Create a base 12 calculator with different limits at diferent digits with python

I want o create a calculator that can add (and multiply, divide, etc) numbers in base 12 and with different limits at the different digits.Base 12 sequence: [0,1,2,3,4,5,6,7,8,9,"A","B&q…

Python Program to check if a number is armstrong or not is not working, what am I doing wrong?

n=int(input("Enter a Number: ")) x=0 y=0 z=0while(n>0):x=n%10y=x**3z=z+yn=n//10print (z) #The z here is the same value which I enter, yet it doesnt work. #If I enter 407 as n, z becomes (4…

Python(Scrapy) unpredictable mistake with import load_entry_point

I have such problem, I did nothing with Python or Scrapy, but when I started today my computer I got such error. I have found many different posts and tried some tips and advices, unfortunately, they a…