Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #3238

Re: Pythonic infinite for loop?

References <BANLkTi=x=HKoPeimLr0qh2+fLTaViG3=dA@mail.gmail.com>
Date 2011-04-14 21:41 -0500
Subject Re: Pythonic infinite for loop?
From John Connor <john.theman.connor@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.380.1302835283.9059.python-list@python.org> (permalink)

Show all headers | View raw


If I understand  your question correctly, what you want is probably
something like:

i = 0
lst=[]
while True:
 try:
   lst.append(parse_kwdlist(dct["Keyword%d"%i]))
   i += 1
 except KeyError:
   break

--jac

On Thu, Apr 14, 2011 at 9:10 PM, Chris Angelico <rosuav@gmail.com> wrote:
> Apologies for interrupting the vital off-topic discussion, but I have
> a real Python question to ask.
>
> I'm doing something that needs to scan a dictionary for elements that
> have a particular beginning and a numeric tail, and turn them into a
> single list with some processing. I have a function parse_kwdlist()
> which takes a string (the dictionary's value) and returns the content
> I want out of it, so I'm wondering what the most efficient and
> Pythonic way to do this is.
>
> 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? (Sounds like I'm risking the numbers
> evaporating or something.) And two, can the entire thing be turned
> into a list comprehension or something? Generally any construct with a
> for loop that appends to a list is begging to become a list comp, but
> I can't see how to do that when the input comes from a dictionary.
>
> In the words of Adam Savage: "Am I about to feel really, really stupid?"
>
> Thanks in advance for help... even if it is just "hey you idiot, you
> forgot about X"!
>
> Chris Angelico
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Back to comp.lang.python | Previous | Next | Find similar


Thread

Re: Pythonic infinite for loop? John Connor <john.theman.connor@gmail.com> - 2011-04-14 21:41 -0500

csiph-web