gpt4 book ai didi

python - 如何从 python 中的数组中获取匹配的记录?

转载 作者:行者123 更新时间:2023-11-28 22:17:21 25 4
gpt4 key购买 nike

我在 python 中有一个以下数组。我想检索带有 id 的记录。除了通过遍历所有记录来检查每条记录的 id 字段之外,有没有办法做到这一点。有更好的方法吗?

[
{
'id': 'zy0Wk',
'name': 'vendor_change_order_status.txt',
'path': 'templates/messages/vendor_change_order_status.txt'
},
{
'id': 'JTo8c',
'name': 'vendor_change_order_status_accepted.txt',
'path': 'templates/messages/vendor_change_order_status_accepted.txt'
},
]

最佳答案

如果您只是进行一次查找,那么没有什么比逐条检查记录更好的了。

但是,如果您要对同一数据进行很多查找,您需要将该列表转换为字典,以 id 为键:

lst = [
{
'id': 'zy0Wk',
'name': 'vendor_change_order_status.txt',
'path': 'templates/messages/vendor_change_order_status.txt'
},
{
'id': 'JTo8c',
'name': 'vendor_change_order_status_accepted.txt',
'path': 'templates/messages/vendor_change_order_status_accepted.txt'
},
]
dct = {element['id']: element for element in lst}

现在,您可以更简单地查找内容:

thingy = dct['JTo8c']

而且它的效率也高了很多。在列表中查找内容需要线性时间——您必须将它与列表中的每个元素进行比较。在哈希表中查找内容(字典在幕后使用的内容)需要固定的时间 — 您对其进行哈希处理,然后进行一次比较,然后您就知道它存在或不存在。1


<子>1。这不是完全正确的,因为不同的键可以有相同的散列。但是,如果您在遇到太多碰撞时扩展字典,您最终会得到摊销的恒定时间成本,而 Python 会自动为您完成。

关于python - 如何从 python 中的数组中获取匹配的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51491018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com