Python: how to 'find' something in a list of lists

☆樱花仙子☆ 提交于 2020-01-23 19:21:07

问题


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)


回答1:


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'



回答2:


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'



回答3:


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?




回答4:


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!



来源:https://stackoverflow.com/questions/31169773/python-how-to-find-something-in-a-list-of-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!