[GLLUG] The Python talk reminds me of a question...
Jeremy Bowers
jerf at jerf.org
Mon Aug 16 17:18:18 EDT 2004
Ashton Shortridge wrote:
> Here comes the question. I want to return ALL of the titles. Intuitively (but
> wrongly), I tried:
> db[:][4]
> which returns an error that basically says there is no 4th element in the list
> - meaning the list called db, which only contains two things. Other stabs
> also met with failure.
>
> So, the question is, how can I refer to the nth elements of ALL records?
The easiest way will be a list comprehension:
[x[4] for x in db]
Having a real example based on your code and needs might help you
understand them better, as they are somewhat unusual.
That is equivalent to:
x = []
for _ in db:
x.append(_[4])
where I use "_" because that variable never actually exists.
> If
> the answer is: "hey silly, use a different data structure!" , then just tell
> me about that structure.
Even if you use a different data structure, this is still often the
right answer, the expression in front just changes. A class might read as
[x.title for x in db]
(If you have further followup questions, please feel free to email me,
but we should probably take it off-list.)
More information about the linux-user
mailing list