在列表中找到一个元素,并给出相应的元素

问题描述 投票:0回答:1

我想在I2C扫描器中实现简单的查找功能。最终,它应该由电池供电,并带有小的OLED显示屏,以测试生产中的设备并进行故障排除。我的I2C扫描仪以十六进制地址输出找到的设备列表,例如['0x3c','0x48']我的想法是使用清单的已知设备= [(address1,Description1),(address2,Description2)]我是python的初学者,所以有点卡住了。我确实知道如何使用if 'x' in 'list'在“正常”列表中查找单个值,但是使用更多设备,这将非常庞大。我想遍历设备列表,并在与“数据库”匹配时打印出类似'found <description1> at address <address1>'

的内容
python list search sensors
1个回答
0
投票

让Python为您完成工作,并将地址映射到字典中的描述:

desc = {"0xaa": "Proximity 1", "0xbb": "Motion 1"} # And so on
# If you really want a function that does the job (not necessary) then:
get_description = desc.get # Maximize the access speed to the dict.get() method
# The method get works as follows:
desc.get("0xaa", "Unknown device")
# Or you can call it as:
get_description("0xbb", "Unknown device")
# The method gives you the possibility to return the default value in case the key is not in the dictionary
# See help(dict.get)
# But, what you would usually do is:
desc["0xaa"] # Raises an KeyError() if the key is not found
# If you really need a function that returns a list of addr, desc tuples, then you would do:
def sensors ():
    return [(x, get_description(x, "Unknown device") for x in get_addresses()]

# Which is short and efficient for:
def sensors ():
    sensors_list = []
    for x in get_addresses():
        tpl = (x, get_description(x, "Unknown device"))
        sensors_list.append(tpl)
    return sensors_list

从字典中获取值非常快速有效。您不应该有时间或记忆问题。您可以使用多种方法来使用索引而不是dict()来加快处理速度,但是请相信我,如果您对内存和/或速度没有太大的限制,则不值得花时间进行编码来获取它对。

© www.soinside.com 2019 - 2024. All rights reserved.