performance - 如何从字典中的字典获取数据,避免在python中使用for循环
问题描述
数据示例:
response = {
"took" : value1,
"_shards" : {
"total" : 2,
},
"hits" : {
"total" : {
"value" : 150,
},
"hits" : [
{
"_index" : "index1",
"_type" : "_doc",
"_source" : {
"date" : "date1",
"hit" : 1,
"routing-key" : "id_key1",
"data": vector1[0:299]
},
},
{
"_index" : "index2",
"_type" : "_doc",
"_source" : {
"date" : "date2",
"hit" : 2,
"routing-key" : "id_key2",
"data": vector2[0:299]
},
},
{
"_index" : "index3",
"_type" : "_doc",
"_source" : {
"date" : "date3",
"hit" : 3,
"routing-key" : "id_key3",
"data": vector3[0:299]
},
},
#...
# I am not going to copy the whole request but there are until 150 hits
#...
]
}
}
现在我想从请求中的所有命中中获取位置 120 中的“数据”的值:vector[0:299]
我已经尝试做
vect_sol = response['hits']['hits'][:]['_source']['data'][120]
但我得到了错误
TypeError: list indices must be integers or slices, not str
要获取我使用过的“命中”字典中的索引
vect_sol = response['hits']['hits'][:]
它有效。for
那么我如何通过循环在数据向量中获得所需的值
for i in range(hits):
data_sol[i] = response['hits']['hits'][i]['_source']['data'][120]
这工作正常,但是当数据请求由 10,000 次或更多(可能更大)组成时,脚本需要时间来填充data_sol
向量。
我猜是否有某种功能或不同的方式可以将数据作为请求获取,但会缩短脚本的执行时间。
解决方案
您可以使用 Python理解列表(尽管这可以被视为一个循环):
vect_sol = [item['_source']['data'][120] for item in response['hits']['hits']]
如果您不需要遍历完整的数据结构,您可以使用 Python生成器(惰性):
vect_sol = (item['_source']['data'][120] for item in response['hits']['hits'])
或者,您可以使用更面向功能的代码(可能更快)map
:
vect_sol = map(lambda item: item['_source']['data'][120], response['hits']['hits'])
如果您想要更快的代码,我认为您应该将数据结构转换为相互关联的对象(定义明确的类)。这应该比使用带有字符串键(需要散列)的 Python 字典(散列映射)快得多。
推荐阅读
- javascript - 如何将 Base64 编码的字符串转换为可以在 chrome 浏览器中显示的任何其他图像格式
- python - python elasticsarch集成
- typo3 - TYPO3 Extbase 表单引用者大小写错误
- python - 如何对包含在对象中的列表进行排序
- excel - 仅在过滤的范围/单元格上使用 IFERROR 和 VLOOKUP(动态公式/代码)
- c# - 在c#中达到一定大小时创建csv文件
- python-3.x - Python3 - 从文件中读取混合数据并将读取的值转换为浮点数
- azure - Azure B2C 未将电子邮件地址作为输入声明发送到 REST API 验证服务
- javascript - 我正在尝试使用 javascript 进行表单验证,但电子邮件验证不起作用
- spring - Spring Boot 捕获多个异常并作为错误响应发送