Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #13123 > unrolled thread
| Started by | Tim Chase <python.list@tim.thechases.com> |
|---|---|
| First post | 2011-09-11 07:41 -0500 |
| Last post | 2011-09-11 07:41 -0500 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Idioms combining 'next(items)' and 'for item in items:' Tim Chase <python.list@tim.thechases.com> - 2011-09-11 07:41 -0500
| From | Tim Chase <python.list@tim.thechases.com> |
|---|---|
| Date | 2011-09-11 07:41 -0500 |
| Subject | Re: Idioms combining 'next(items)' and 'for item in items:' |
| Message-ID | <mailman.984.1315744926.27778.python-list@python.org> |
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 top | Article view | comp.lang.python
csiph-web