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

如何将字典中所有二维值拼接为PyTorch张量?

将字典中二维数组按行拼接为PyTorch张量的解决方案

可以通过以下简洁步骤实现需求:

  1. 把字典内的每个二维列表转换为PyTorch张量
  2. 沿着**列维度(dim=1)**拼接所有张量(所有输入的行数一致,满足拼接前提)

完整代码如下:

import torch

D = {'a': [[0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0]],
     'b': [[1, 1],
           [1, 1],
           [1, 1]],
     'c': [[2, 2, 2, 2],
           [2, 2, 2, 2],
           [2, 2, 2, 2]]
}

# 转换字典值为张量列表
tensor_list = [torch.tensor(matrix) for matrix in D.values()]
# 沿列维度拼接张量
output_tensor = torch.cat(tensor_list, dim=1)

print(output_tensor)

运行后会输出预期结果:

tensor([[0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2],
        [0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2],
        [0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2]])

关键说明

  • torch.tensor()负责将Python二维列表转换为PyTorch张量,完整保留原二维结构
  • torch.cat()的dim=1参数指定拼接方向为列方向,确保每一行的元素按顺序合并;若误设为dim=0则会按行堆叠,不符合需求

内容的提问来源于stack exchange,提问作者core_not_dumped

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 17:01:06