Python:如何在列表列表中“查找"某物 [英] Python: how to 'find' something in a list of lists

查看:123
本文介绍了Python:如何在列表列表中“查找"某物的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,您可以执行以下操作:

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"]]

我想搜索名称"John"并找出州和ID号,而无需遍历列表的所有元素?我要寻找的是是否类似于"L中的{ifthing}".

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".

我想这就像一个记录搜索功能.我有一个列表列表,元素是固定长度的列表(或元组),我想看看Python中是否有O(1)类型的搜索功能,或者我可以轻松实现的功能一步搜索(假定为O(N),它需要遍历列表中的所有元素)

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)

推荐答案

您应该创建并使用字典.

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}

这可以轻松查找:

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

这篇关于Python:如何在列表列表中“查找"某物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆