You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 10:24:01