Namedtuples problem
Deborah Swanson
python at deborahswanson.net
Thu Feb 23 20:34:43 EST 2017
MRAB wrote, on Thursday, February 23, 2017 4:06 PM
>
> On 2017-02-23 23:00, Deborah Swanson wrote:
> >
> >
> >> -----Original Message-----
> >> From: Erik [mailto:python at lucidity.plus.com]
> >> Sent: Thursday, February 23, 2017 2:09 AM
> >> To: python at deborahswanson.net; python-list at python.org
> >> Subject: Re: Namedtuples problem
> >>
> >>
> >> Hi,
> >>
> >> On 23/02/17 09:38, Deborah Swanson wrote:
> >> > group[[idx][records_idx[label]]]
> >> > gets an IndexError: list index out of range
> >>
> >> [snip]
> >>
> >> > Can anyone see why I'm getting this Index error? and how
> to fix it?
> >>
> >> It looks to me like you are indexing into a single-element
> list that
> >> you are creating using the literal list syntax in the middle of
> >> the expression.
> >
> > Actually, group is essentially a 2-element list. Each group
> has a list
> > of rows, and each row has a set of fields. group has to be
> indexed by
> > row index and field index. (This is a namedtuple configuration.)
> >
> > The weirdness is that
> >
> > group[0][4]
> >
> > gets the right answer, but
> >
> > group[[idx][records_idx[label]]],
> > where idx = 0 and records_idx[label]] = 4
> >
> > gets the IndexError.
> >
> It's not weird. As Erik says below, and I'll repeat here, you have:
>
> group[[idx][records_idx[label]]]
>
> That consists of the expression:
>
> [idx][records_idx[label]]
>
> within:
>
> group[...]
>
> The [idx] creates a one-element list.
Yes, group[idx] gives you a row from group
> You then try to subscript it with records_idx[label]. If
> records_idx[label] is anything other than 0 (or -1), it'll raise
> IndexError because there's only one element in that list.
No, there are currently 17 elements in a record that records_idx[label]
could be referring to in my running code, depending on which field
'label' refers to. Please see the breakdown of what a typical group
looks like that I gave Steve. If you can't find it, let me know and I'll
repeat it.
> If you substitute idx == 0 and records_idx[label]] == 4 into:
>
> group[[idx][records_idx[label]]]
>
> you'll get:
>
> group[[0][4]]
>
> which is not the same thing as group[0][4]!
No it isn't! And that's probably where the mysterious IndexError is
coming from! Sickening how crosseyed I can get working with these things
for too long at a stretch.
And in fact, deleting that outer set of square brackets not only get's
rid of the IndexError, but group[idx][records_idx[label]] now fers to
the correct set of field values I was trying to access.
Thank you, thank you!
<snip>
More information about the Python-list
mailing list