如何将numpy数组拆分后存入字典对应键的列表中
实现方法
你可以先通过reshape方法将长度为12的a数组调整为3行4列的二维数组,再遍历键名数组和拆分后的子数组,依次存入字典即可,具体代码如下:
import numpy as np set_names = np.array(['one', 'two', 'three']) a = np.array([12,4,2,45,6,7,2,4,5,6,12,4]) dictionary = {} # 拆分数组为3个长度为4的子数组 split_arr = a.reshape(3, 4) # 遍历对应键值对存入字典 for k, v in zip(set_names, split_arr): dictionary[k] = v.tolist()
执行后打印dictionary即可得到你需要的输出:
{'one': [12, 4, 2, 45], 'two': [6, 7, 2, 4], 'three': [5, 6, 12, 4]}
如果需要更简洁的写法,可以直接用字典推导式实现:
dictionary = {k: v.tolist() for k, v in zip(set_names, a.reshape(3, 4))}
内容的提问来源于stack exchange,提问作者georgehere
相关产品推荐
相关产品推荐

