Is there a better way to chose a slice of a list?

Rhodri James rhodri at wildebst.demon.co.uk
Thu May 21 21:12:38 EDT 2009


On Wed, 20 May 2009 17:08:08 +0100, walterbyrd <walterbyrd at iname.com>  
wrote:

> I am processing a huge spreadsheet which I have converted to a csv
> format. Each row will be a wiki page with several sub-headings. The
> spreadsheet contains information about servers. Wiki sub-headings may
> include: 'hardware', 'software', 'users', 'network swith settings'.
> 'Hardware' may include the spreadsheet columns: 'memory', 'cpu', and
> so on. So the first six columns in the spreadsheet may go under
> 'hardware' the next six under 'software' and so on.
>
> I have already created the wiki pages, using a method similar to what
> I first posted. But, it seems like there should be a better way to to
> do it. So, for future reference, I was just wondering.

Given that you're already making presumptions about the nature of your
data, named constants or enums are the most concise thing to use together
with a quick check of the column header row to make sure that the
constants really do refer to the right columns.

If you want something a little more bullet-proof, create a dictionary
mapping the column headers (as read in) to column numbers and use that
to generate the slice limits.  Since that still relies on the column
headers being what you expect them to be, and at least partially in the
order you expect them to be, it's probably not enough of a win to bother
with.

Trying to slice a list by value is never going to look pretty because
lists aren't designed to be indexed by value.  Worse, if you were
doing this a lot (as you imply) then it's going to be horribly
inefficient, since you're doing an extra two (or more) O(n) searches
for every row.

-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list