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


Groups > comp.lang.python > #3237

Re: Pythonic infinite for loop?

Subject Re: Pythonic infinite for loop?
From Ryan Kelly <ryan@rfk.id.au>
References <BANLkTi=x=HKoPeimLr0qh2+fLTaViG3=dA@mail.gmail.com>
Date 2011-04-15 12:34 +1000
Newsgroups comp.lang.python
Message-ID <mailman.379.1302834871.9059.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

On Fri, 2011-04-15 at 12:10 +1000, Chris Angelico 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.)

There is, use an infinite generator:

  def ints_from(start):
      while True:
          yield start
          start += 1


  for i in ints_from(1):
       ..etc...


But why not just put the while loop inline:

  i = 0
  while True:
      try:
          ...etc...
      except KeyError:
          break
      i += 1

It might be even easier to just iterate through the dictionary keys:

  for k in sorted(dct.keys()):
      if k.startswith("Keyword"):
          lst.append(parse_kwdlist(dct[k]))


>  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.

You probably could, but I think it would hurt readability in this case:

  lst = [parse_kwdlist(dct[k]) for k in sorted(dct.keys())
                               if k.startswith("Keyword")]


  Cheers,

    Ryan

-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
ryan@rfk.id.au        |  http://www.rfk.id.au/ramblings/gpg/ for details

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


Thread

Re: Pythonic infinite for loop? Ryan Kelly <ryan@rfk.id.au> - 2011-04-15 12:34 +1000

csiph-web