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

2024-04-29 12:33:51 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 功能列表电池地址i2c故障扫描仪元组
1条回答
网友
1楼 · 发布于 2024-04-29 12:33:51

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

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

list(desc.items())

生成的列表将与my sensors()函数中的列表相同,但它将始终返回所有设备,无论它们是否存在。此外,如果您同时添加了一个新设备,而该设备不在词典中,则它不会作为“未知设备”出现在结果列表中

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

例如,如果要按描述的字母顺序显示所有可能的设备,可以执行以下操作:

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”),以了解此代码的工作原理

相关问题 更多 >