gpt4 book ai didi

python - 如何将多个numpy数组组合成一个字典列表

转载 作者:太空宇宙 更新时间:2023-11-03 13:26:33 29 4
gpt4 key购买 nike

我有以下数组:

column_names = ['id', 'temperature', 'price']

和三个numpy数组如下:

idArry = ([1,2,3,4,....])

tempArry = ([20.3,30.4,50.4,.....])

priceArry = ([1.2,3.5,2.3,.....])

我想把上面的组合成一个字典如下:

table_dict = ( {'id':1, 'temperature':20.3, 'price':1.2 },
{'id':2, 'temperature':30.4, 'price':3.5},...)

我可以使用 for 循环和 append 来创建字典,但列表很大,大约有 15000 行。有人可以告诉我如何使用 python zip 功能或其他更高效、更快速的方法来实现上述要求吗?

最佳答案

您可以使用 listcomp 和函数 zip():

[{'id': i, 'temperature': j, 'price': k} for i, j, k in zip(idArry, tempArry, priceArry)]
# [{'id': 1, 'temperature': 20.3, 'price': 1.2}, {'id': 2, 'temperature': 30.4, 'price': 3.5}]

如果您的 ID 是 1、2、3...,并且您使用的是列表,那么您的字典中不需要 ID。这是列表中的冗余信息。

[{'temperature': i, 'price': j} for i, j in zip(tempArry, priceArry)]

您也可以使用字典中的字典。字典中的查找必须比列表中的查找更快。

{i: {'temperature': j, 'price': k} for i, j, k in zip(idArry, tempArry, priceArry)}
# {1: {'temperature': 20.3, 'price': 1.2}, 2: {'temperature': 30.4, 'price': 3.5}}

关于python - 如何将多个numpy数组组合成一个字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54607437/

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