python - 以矩阵形式将列表排列到numpy数组

标签 python arrays numpy

我有一个列表:

rs = list([[(0, 167, 159, 0), (1, 168, 160, 1)], [(0, 167, 159, 1), (1, 168, 160, 0)]])

我想把它排列成矩阵形式的numpy数组,所以我写了下面的代码:

import numpy

rs = list([[(0, 167, 159, 0), (1, 168, 160, 1)], [(0, 167, 159, 1), (1, 168, 160, 0)]])
k = 2
j = 0
h = 0
ars = []
element = list(rs)
ck_dist_m = numpy.array([[]], ndmin = 2)

while j <= k - 1:
    while h <= k - 1:
        rp = numpy.array(element[j][h][3], ndmin = 2)
        ars.append(rp)
        h = h + 1
    else:
        h = 0
        ck_dist_m = numpy.vstack(ars)
    j = j + 1
print ck_dist_m

我想要的结果是:

[[0, 1],
 [1, 0]]

但是上面的脚本给出了这个:

[[0]
 [1]
 [1]
 [0]]

如何编辑脚本得到矩阵形式的结果?

最佳答案

In the while loop I extract the third element in the sublist, and try to store them in matrix form.

这里有一个更直接的方法来实现这一点:

>>> numpy.array(rs)[:,:,3]
array([[0, 1],
       [1, 0]])

关于python - 以矩阵形式将列表排列到numpy数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40234158/

相关文章:

python - 一次使用 Pandas 返回多只股票

arrays - Delphi 5.0 Pascal 中数组从 0 或 1 开始?

python - 使用 timedelta 将一个月添加到 datetime64

python-3.x - 类型错误 : conversion from Series to Decimal is not supported

python - numpy "Mean of empty slice."警告

python - Scikit-learn:避免高斯过程回归中的过度拟合

python - ImportError : No module named absl.测试

python - 尝试在 python 中有效地计算相关矩阵

python - 如何使用 Cython 将 Python 列表传递给 C 函数

javascript - 获取具有特定属性的对象列表