[Tutor] Fastest find in 2 2D lists with else statement

Mark Lawrence breamoreboy at yahoo.co.uk
Fri Mar 20 22:05:30 CET 2015


On 20/03/2015 12:22, Kale Good wrote:
> Hello all,
> I'm new to python and a bit of a weekend-warrior programmer (guitar
> teacher by trade), so there are plenty of computer sciencey concepts
> that I haven't grasped yet, and I think I'm bumping up against those now.

Welcome to the club :)

>
> Read from separate csv files, I have something like
>
>      a=[['bass',9],['eagle',36],['human',68]]
>      b=[['bass','fish'],['eagle','bird'],['dog',land']]
>      c=[[1,'fish','water'],[2, 'mammal','land'],[3,'bird','air']]
>
> What I want is to return where each animal lives. What I've been able to
> glisten from the manuals and stack overflow is:
>
> for i in range(len(a)):
>
>          for x in range(len(b)):
>            if a in b[x][1]:
>               clss = (b[x][0])
> occurrence  w/ else statement
>          for y in range(len(c)):
>             if clss in c[y][1]:
>                place = (c[y][2])
>
>          a[i].append(place)
>

Classic newbie stuff that immediately flags up a code smell.  You do not 
need to loop around Python containers using indexes.  This is typically 
written something like.

for animal in animals:
     doSomething(animal)

However see my comment below, you probably don't need so many loops if 
you hold your data in dicts.

> a)I'd like to have an else statement; if a match isn't found in b,
> prompt the user for one of the values in c[:][0]. (no need to print the
> list c; the user will have that available elsewhere)
>
> b)Is there a faster way to do this? List a has ~300 elements, while list
> b has ~45000, so I'm curious if I can make it faster.

Take a look at the DictReader here 
https://docs.python.org/3/library/csv.html as when it comes to looking 
things up dicts are far faster than lists.  Try coding it up and come 
back to us if you get any problems.  We don't bite although I have been 
known to bark :)

>      -I only need to find the first match, so it seems a next statement
> would do the trick. However, I can't figure out how to use next for
> finding in two 2d arrays.
>     -From my understanding, for this use, b needs to be a list. However,
> each line is unique, so it could be a set if necessary.
>
> Thanks in advance.
>
> Best,
> Kale

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list