我有这些数据
data = [
{
'id': 'abcd738asdwe',
'name': 'John',
'mail': 'test@test.com',
},
{
'id': 'ieow83janx',
'name': 'Jane',
'mail': 'test@foobar.com',
}
]
id是唯一的,不可能多个听写都有相同的id
例如,我想获取id为“ieow83janx”的项。你知道吗
我当前的解决方案如下所示:
search_id = 'ieow83janx'
item = [x for x in data if x['id'] == search_id][0]
你认为这是最好的解决方案还是有人知道其他的解决方案?你知道吗
由于
id
是唯一的,因此可以将这些项存储在字典中以实现O(1)查找。你知道吗那你就可以了
去找回它
next
内置函数(docs)如何:编辑:
如果找不到匹配项,则会引发
StopIteration
,这是处理缺勤的一种很好的方法:如果要对这个特定对象多次执行此类操作,我建议将其转换为以
id
为键的字典。你知道吗在这种情况下,此查找操作将花费一些固定的*
O(1)
时间,而不是O(N)
。你知道吗相关问题 更多 >
编程相关推荐