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


Groups > comp.lang.python > #3271

Re: Pythonic infinite for loop?

Date 2011-04-15 06:56 -0700
From Ethan Furman <ethan@stoneleaf.us>
Subject Re: Pythonic infinite for loop?
References <BANLkTi=x=HKoPeimLr0qh2+fLTaViG3=dA@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.394.1302875810.9059.python-list@python.org> (permalink)

Show all headers | View raw


Chris Angelico wrote:
> 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

Possibly overkill:

import dbf
table = dbf.from_csv("csvfile")   # fields get names f0, f1, f2, ...
table.rename_field('f3', 'key') # or whatever

def keyword_only(record):
     if record.key.startswith('keyword'):
         return int(record.key[len('keyword'):]))
     return dbf.DoNotIndex

keywords = table.create_index(keyword_only)
# keywords is usable as an iterator
for rec in keywords:
     ....

# if you only want the first contiguous records
for i, rec in enum(keywords):
     if rec.key != 'keyword%d' % enum:
         break
     ...

Disclosure: I am the author of the dbf module.

Depending on your needs for the other fields of the csv file, this might 
be an easier way to access them.  Field names can also be specified when 
opening the csv file, I didn't bother for this example since I don't 
know what all your field names are.  ;)

Hope this helps!

~Ethan~

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


Thread

Re: Pythonic infinite for loop? Ethan Furman <ethan@stoneleaf.us> - 2011-04-15 06:56 -0700

csiph-web