HowTo Search in nested lists
Christopher Koppler
klapotec at chello.at
Fri Jan 30 19:05:40 CET 2004
On Fri, 30 Jan 2004 18:11:12 +0100, Florian Lindner
<Florian.Lindner at xgm.de> wrote:
>Hello,
>I've two nested lists which are representing a table or matrix.
>
>A = [1, 2, 3]
>B = [4, 5, 6]
>C = [7, 8, 9]
>
>t = [A, B, C]
>
>print t[0][2] # Prints 3
>
>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
>
>I hope I could explain what I want. Is there any way to do that except:
>
>for i in len(t):
> if t[i][1] == "phrase":
> found = i
> break
Well, for a structurally similar approach to yours, first let's get
rid of len. Python is not [C, Pascal, Basic, Java, whatever], lists
can and should be iterated on directly. And 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.
>>> t = [[1,2,3],[4,5,6],[7,8,9],[2,5,8]]
>>>
>>> def search_nested_list(nested_list, column, value_to_search_for):
... result = []
... for lst in nested_list:
... if lst[column] == value_to_search_for:
... result.append(lst)
... return result
...
>>> x = search_nested_list(t, 1, 5)
>>> x
[[4, 5, 6], [2, 5, 8]]
If you only want to know whether any of the lists contains the value
you look for, without caring which ones, you can instead do it like
this:
>>> def search_nested_list(nested_list, column, value_to_search_for):
... for lst in nested_list:
... if lst[column] == value_to_search_for:
... return True # or 1 for Python < 2.3
...
>>> x = search_in_nested_list(t, 1, 5)
>>> x
True
Grok it, and then get rid of the unnecessary long names ;-)
Or you could of course also do it with a list comprehension:
Either:
>>> [lst for lst in t if lst[1] == 5]
[[4, 5, 6], [2, 5, 8]]
Or:
>>> [True for x in t if x[1] == 5]
[True, True]
where the length of the result also tells you how often the result was
found.
Getting the last example to only return True once for multiple hits
and making functions of the list comprehensions is left as an exercise
to the reader...
--
Christopher
More information about the Python-list
mailing list