python - 提高python中重复代码的效率
问题描述
我需要在python中进行以下操作:
我有一个元组列表
data = [("John", 14, 12132.213, "Y", 34), ("Andrew", 23, 2121.21, "N", 66)]
我有一个字段列表:
fields = ["name", "age", "vol", "status", "limit"]
每个数据元组按顺序用于每个字段。
我有一个字典
desc = { "name" : "string", "age" : "int", "vol" : "double", "status" : "byte", "limit" : "int" }
我需要生成一条按以下格式发送的消息:
[{"column": "name", "value": {"String": "John"}}, {"column": "age", "value": {"Int": 14}}, {"column": "vol", "value": {"Double": 12132.213}}, {"column": "status", "value": {"Byte": 89}}, {"column": "limit", "value": {"Int": 34}},
{"column": "name", "value": {"String": "Andrew"}}, {"column": "age", "value": {"Int": 23}}, {"column": "vol", "value": {"Double":2121.21}}, {"column": "status", "value": {"Byte": 78}}, {"column": "limit", "value": {"Int": 66}}]
我有两个生成这个的函数:
def get_value(data_type, res):
if data_type == 'string':
return {'String' : res.strip()}
elif data_type == 'byte' :
return {'Byte' : ord(res[0])}
elif data_type == 'int':
return {'Int' : int(res)}
elif data_type == 'double':
return {'Double' : float(res)}
def generate_message(data, fields, desc):
result = []
for row in data:
for field, res in zip(fields, row):
data_type = desc[field]
val = {'column' : field,
'value' : get_value(data_type, res)}
result.append(val)
return result
然而,数据真的很大,有大量的元组(~200,000)。为它们中的每一个生成上述消息格式需要花费大量时间。有没有一种有效的方法来做到这一点。
PS 需要这样的消息,因为我在队列上发送此消息,而消费者是需要类型信息的 C++ 客户端。
解决方案
以aydow的答案为基础并加快速度:
dt_action = {
'string': (lambda res: {'String': res.strip()}),
'byte': (lambda res: ord(res[0])),
'int': (lambda res: int(res)),
'double': (lambda res: float(res)),
}
def generate_message_faster(data, fields, desc):
return [
{'column': field, 'value': dt_action[desc[field]](res)}
for row in data for field, res in zip(fields, row)
]
时间:
- 原来的
6.44 µs per loop
- 与
dt_action
:5.54 µs per loop
- 并
dt_action
列出comp:4.92 µs per loop
推荐阅读
- string - 在matlab中比较字符串
- python - 在网站的不同页面上放置不同的背景图像
- typescript - 在 tsconfig.json 中设置“include”属性后,出现错误
- nginx - Nginx:基于 LUA Redis 的块内容 URL(.MP4 或 .PNG)
- javascript - 添加总数;预算应用程序,原生 JavaScript
- cloud-foundry - Geode/GemFire 无法创建 gemfireCache bean 错误:Spring Boot v2.1.3 - GemFire starter 1.1.0.RELEASE
- python - 澄清类型错误:“str”对象不可调用
- javascript - 有没有办法从一个名为 admin.htm 的页面创建元素来创建 index.html 的输入文本两者都在同一个文件夹中
- java - 如何使用错误响应休息模板处理 200 状态码?
- javascript - WebGL 中纹理、缓冲区和其他对象的组织