Pythonic infinite for loop?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Apr 14 22:33:46 EDT 2011
On Fri, 15 Apr 2011 12:10:52 +1000, Chris Angelico wrote:
> Apologies for interrupting the vital off-topic discussion, but I have a
> real Python question to ask.
Sorry, you'll in the wrong forum for that.
*wink*
[...]
> My first draft looks something like this. The input dictionary is called
> dct, the output list is lst.
>
> lst=[]
> for i in xrange(1,10000000): # arbitrary top, don't like this
> try:
> lst.append(parse_kwdlist(dct["Keyword%d"%i]))
> except KeyError:
> break
>
> I'm wondering two things. One, is there a way to make an xrange object
> and leave the top off?
No. But you can use an itertools.count([start=0]) object, and then catch
the KeyError when you pass the end of the dict. But assuming keys are
consecutive, better to do this:
lst = [parse_kwdlist(dct["Keyword%d"%i]) for i in xrange(1, len(dct)+1)]
If you don't care about the order of the results:
lst = [parse_kwdlist(value) for value in dct.values()]
--
Steven
More information about the Python-list
mailing list