python - 如何将元组列表列表(索引,值)转换为 2D numpy 数组
问题描述
有元组列表列表:
[[(0, 0.5), (1, 0.6)], [(4, 0.01), (5, 0.005), (6, 0.002)], [(1,0.7)]]
我需要得到矩阵 X x Y:
x = num of sublists
y = max among second eleme throught all pairs
elem[x,y] = second elem for x sublist if first elem==Y
0 | 1 | 2 | 3 | 4 | 5 | 6 |
---|---|---|---|---|---|---|
0.5 | 0.6 | 0 | 0 | 0 | 0 | 0 |
0 | 0 | 0 | 0 | 0.01 | 0.005 | 0.002 |
0 | 0.7 | 0 | 0 | 0 | 0 | 0 |
解决方案
您可以通过以下方式计算数组的尺寸。Y维度是子列表的数量
>>> data = [[(0, 0.5), (1, 0.6)], [(4, 0.01), (5, 0.005), (6, 0.002)], [(1,0.7)]]
>>> dim_y = len(data)
>>> dim_y
3
X 维度是[0]
所有元组的最大索引加 1。
>>> dim_x = max(max(i for i,j in sub) for sub in data) + 1
>>> dim_x
7
所以然后用这个大小初始化一个全零的数组
>>> import numpy as np
>>> arr = np.zeros((dim_x, dim_y))
>>> arr
array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
现在填充它,enumerate
在您的子列表上跟踪 y 索引。然后对于每个子列表,使用[0]
x 索引和[1]
值本身
for y, sub in enumerate(data):
for x, value in sub:
arr[x,y] = value
然后应该填充生成的数组(可能想要转置以看起来像您想要的尺寸)。
>>> arr.T
array([[0.5 , 0.6 , 0. , 0. , 0. , 0. , 0. ],
[0. , 0. , 0. , 0. , 0.01 , 0.005, 0.002],
[0. , 0.7 , 0. , 0. , 0. , 0. , 0. ]])
推荐阅读
- reactjs - 在本地尝试此代码框时,我收到此错误缺少 index.htm 文件
- javascript - 如何使用 JS 知道特定键盘位置上的字符
- flutter - Flutter/Dart 如何选择日期并使用选择填充文本字段
- html - src 指向文件夹而不是文件?
- graphql - gatsby-source-ghost 无法在 Gatsby 中创建 Ghost 模式
- git - git push 错误 - 无法写入包文件
- tcl - Tcl 二进制扫描未设置字节
- java - 如何将文本文件读入Java中的数组列表?
- python - 用户将获得不同的分数,具体取决于哪些尝试正确解决他们的问题
- linux - 如何修复 crond [296824]:在 /root/.esmtprc 或 /etc/esmtprc 中找不到配置文件?