list index question

fedor fedor at mailandnews.com
Wed Apr 30 23:11:15 CEST 2003


> > Can I wildcard? I don't know the values in the second column.  I want
> > to find the first entry what has a particular value in the first
> > column.

> The list.index() function won't help you, then: it just does a strict
> equality comparison. You'll have to write a simple loop:
>
>     index = -1
>     for item in sql_result_list:
>         index += 1
>         if item[0] == 100:
>             print "Found it"
>             break
>     if index >= len(sql_result_list):
>         print "Not found"
>
> I know you said you wanted to avoid looping, but this may not be
> possible. Why did you want to avoid looping, anyway?
>
> Another thing you may not have thought of is to loop through your
> results once and build a dict that you could use for lookup:
>
>     index_dict = {}
>     for item in sql_result_list:
>         key = item[0]
>         index_dict[key] = item
>
> Now you can use index_dict to do O(1) lookups based on the first item of
> each tuple. Note that as written, though, only *one* item with the same
> key will be kept. There are other ways around that, but I'm getting a
> bit far off your original question.
>

If you realy want to avoid you can use the less eficient:

>>> list1=[(100,1),(100,10),(101,1),(101,5)]
>>> zip(*list1) #transpose
[(100, 100, 101, 101), (1, 10, 1, 5)]
>>> list(zip(*list1)[0]).index(100) #select the first column and transform
it into a list (because a tuple doesn't have an index function)
0







More information about the Python-list mailing list