在元组列表中查找一个元素,并给出对应的元组

Find an element in a list of tuples, and give out the corresponding tuple

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

的内容

让 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() 来加快速度,但是相信我,如果你不是很受内存 and/or 速度的限制,那么不值得花时间和编码来修正它。 例如,此方法包括按照这样的顺序生成 I2C 地址,以便您的算法可以将它们缩小到包含相应描述的 tuple() 的索引。这取决于您对 I2C 设备地址的控制程度。简而言之,您将构建一个查找 table 并以类似的方式使用它 作为三角函数。一项简单的任务需要大量工作。我查看了 MPython 和您正在使用的 MCU,您肯定有足够的资源来使用标准的 Pythonic 方法来完成您的任务,即:字典。

此外,我必须解释一下,在示例函数 get_addresses() 下,我指的是检测当时存在的设备的函数。因此,如果您出于某种原因需要一个元组列表,并且您的设备始终存在,您可以这样做:

list(desc.items())

结果列表与我的 sensors() 函数相同,但它总是 return 所有设备,无论它们是否存在。此外,如果您同时添加了一个不在字典中的新设备,它将不会作为 "Unknown device".

出现在结果列表中

您还应该知道,出于优化原因,dict() 数据类型是无序的。这意味着 list(desc.items()) 不会按照您在 dict() 中输入的顺序 return 您的设备的元组。但是我的 sensors() 函数将 return 它们按照想象的 get_addresses() 函数 return 设备地址的顺序排列。

例如,如果您想按描述的字母顺序显示所有可能的设备,您可以这样做:

srtkey = lambda item: item[1]
for address, description in sorted(desc.items(), key=srtkey):
    print("'%s' @ address %s" % (description, address))
    # Of course, you would use the function and/or the algorithm  you use to display the string line

请查看帮助(dict.items)、帮助(sorted) 和帮助("lambda") 以了解此代码的工作原理。