chu1688
chu1688

Reputation: 31

How to 'find' something in a list of lists

In Python, you can do this:

L=["John","David","Susan"]
x = "John"
if x in L:
    print(L.index(x))

What if I have a list like this:

L = [["John", 1234, "California"], ["David", 5678, "Arizona"], ["Susan", 8765, "Nevada"]]

and I want to do a search of name "John" and find out the State and ID number without iterating over all the elements of the list? What I looking for is if there's something similar to "if {something} in L".

I guess it will be like a record search function. I have a list of lists, the elements are fixed length lists (or tuples), and I want to see if there's a O(1) type of search capability in Python, or something I can implement easily that will be able to do the search in one step (as supposed to O(N), which requres iterating over all the elements in the list)

Upvotes: 2

Views: 9220

Answers (4)

RudyMenon
RudyMenon

Reputation: 36

If L has to be a list of lists, you can always make your own function.

def find(value,matrix):
    for list in matrix:
        if value in list:
            return [matrix.index(list),list.index(value)]
    return -1

Then if you say

L = [["John", 1234, "California"], ["David", 5678, "Arizona"], ["Susan",  8765, "Nevada"]]
x = "John"
if find(x,L) != -1:
    print(find(x,L))

it should print [0,0]

Does this answer your question?

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107347

You can convert your list to set or dictionary that use hash-table and they have order O(1) for checking membership. but this converting is O(n) or more.Also you'll waste more memory!

But as an efficient and direct way I suggest to use a generator expression within next function :

>>> next((j,k) for i,j,k in L if i=='John')
(1234, 'California')

Note that using generators may be not efficient in terms of time but its efficient in memory! and you can save a lot of memory specially when you are dealing with long list!

Upvotes: 1

TigerhawkT3
TigerhawkT3

Reputation: 49330

You should create and use a dictionary.

L = [["John", 1234, "California"], ["David", 5678, "Arizona"], ["Susan", 8765, "Nevada"]]
D = {name:(number, state) for name, number, state in L}

This allows easy lookups:

>>> D.get("John", 'no')
(1234, 'California')
>>> D.get("Jim", 'no')
'no'

Upvotes: 4

Cory Kramer
Cory Kramer

Reputation: 118021

You could make nested dictionaries

>>> d = {i[0]:{'ID':i[1], 'State':i[2]} for i in L}
>>> d
{'Susan': {'ID': 8765, 'State': 'Nevada'},
 'John': {'ID': 1234, 'State': 'California'},
 'David': {'ID': 5678, 'State': 'Arizona'}}

Then lookup a person like

>>> d['John']
{'ID': 1234, 'State': 'California'}
>>> d['John']['State']
'California'

Upvotes: 2

Related Questions