HowTo Search in nested lists

Robert Brewer fumanchu at amor.org
Fri Jan 30 14:11:47 EST 2004


Florian Lindner wrote:
> >I've two nested lists which are representing a table or matrix.
> >Now I found to search for certain values in a certain column.
> >For example: column 1, search for 5, return 1, because 5 is 
> >found in the first column of the second element of t

Christopher Koppler replied:
> ...let's make a function of it that returns the list(s)
> (in case you have more than one list fitting your search
> criteria) containing the searched for value.

Good answers, Christopher. You might consider combining the several
approaches into a single one by creating an iterator; this has the
advantage of functioning identically regardless of whether the consumer
code wants one match or all matches (without traversing the entire list
if only one result is desired). Notice also that the original
requirement called for obtaining the index of the column found, not the
row.

>>> t = [[1,2,3],[4,5,6],[7,8,9],[2,8,5]]
>>>
>>> def positions(nested_list, value):
...     for row in nested_list:
...             try:
...                     yield row.index(value)
...             except ValueError:
...                     pass
...
>>> positions(t, 5).next()
1
>>> [x for x in positions(t, 5)]
[1, 2]


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org




More information about the Python-list mailing list