index of list of lists
Kam-Hung Soh
kamhung.soh at gmail.com
Fri Apr 18 07:37:33 EDT 2008
On Thu, 17 Apr 2008 12:25:51 +1000, Daniel Fetchinson
<fetchinson at googlemail.com> wrote:
>> yes, there's a thread with the same title, but I believe mine is more
>> appropriate title.
>> so, as much as I search on the web, read manuals, tutorials, mail-lists
>> (including this one) I cannot figure it out how to search a string in a
>> list of lists.
>> like this one:
>>
>> someList = [['somestring', 1, 2], ['oneother', 2, 4]]
>>
>> I want to search "somestring" in someList which is in practice a list
>> of aprox. 200 lists. (hey, I'm a newbie python programmer, don't judge
>> me).
>> is the list.index the wrong approach?
>> should I use numpy, numarray, something else?
>> can anyone, be kind and help me with this?
>
> someList = [['somestring', 1, 2], ['oneother', 2, 4]]
> for alist in someList:
> if alist[0] == 'somestring':
> print "Found it at index %d" % someList.index( alist )
> # if you know it will only occur once you might say:
> break
>
> HTH,
> Daniel
See also Section 4.5. Filtering Lists.
List comprehension:
[x for x in someList if x[0] == 'somestring']
Use filter() function:
filter(lambda x: x[0] == 'somestring', someList)
--
Kam-Hung Soh <a href="http://kamhungsoh.com/blog">Software Salariman</a>
More information about the Python-list
mailing list