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


Groups > comp.lang.python > #13123

Re: Idioms combining 'next(items)' and 'for item in items:'

Date 2011-09-11 07:41 -0500
From Tim Chase <python.list@tim.thechases.com>
Subject Re: Idioms combining 'next(items)' and 'for item in items:'
References <j4gea4$m3b$1@dough.gmane.org>
Newsgroups comp.lang.python
Message-ID <mailman.984.1315744926.27778.python-list@python.org> (permalink)

Show all headers | View raw


On 09/10/11 14:36, Terry Reedy wrote:
> 1. Process first item of an iterable separately.
>
> A traditional solution is a flag variable that is tested for each item.
>
> first = True
> <other setup>
> for item in iterable:
>     if first:
>       <process first>
>       first = False
>     else:
>       <process non-first>
>
> (I have seen code like this posted on this list several times, including
> today.)
>
> Better, to me, is to remove the first item *before* the loop.
>
> items = iter(iterable)
> <set up with next(items)
> for item in items:
>     <process non-first>

I like to use this one for processing CSV files where I need to 
clean up the headers:

   r = csv.reader(f)
   headers = r.next()
   header_map = dict(
     (header.strip().upper(), i)
     for i, header
     in enumerate(headers)
     )
   for row in r:
     item = lambda s: row[header_map[s]].strip()
     thing = item("THING")
     whatever = item("WHATEVER")

It's mostly like a DictReader, but it isn't as sensitive to the 
spaces/capitalization that clients love to mess with.

-tkc


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


Thread

Re: Idioms combining 'next(items)' and 'for item in items:' Tim Chase <python.list@tim.thechases.com> - 2011-09-11 07:41 -0500

csiph-web