HowTo Search in nested lists

F

Florian Lindner

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[1] == "phrase":
found = i
break

Thx,
Florian
 
C

Christopher Koppler

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[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
....[[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:
.... for lst in nested_list:
.... if lst[column] == value_to_search_for:
.... return True # or 1 for Python < 2.3
....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, 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...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,265
Latest member
TodLarocca

Latest Threads

Top