【问题标题】:Python - convert list of lists into matrixPython - 将列表列表转换为矩阵
【发布时间】:2019-04-23 18:58:06
【问题描述】:

我正在使用 python,我有一个列表,其中包含一组列表 如何将其转换为一个矩阵?

例如,

Root_List = [list1  list2  list3]
list1 = [1 2 3]
list2 = [1 5 9]
list3 = [2 4 1]

我需要矩阵具有以下值

[
1 2 3
1 5 9
2 4 1
]

有什么想法吗? 提前谢谢你。

【问题讨论】:

  • 问题与keras 无关 - 请不要向标签发送垃圾邮件(已删除)。

标签: python python-3.x numpy arraylist


【解决方案1】:

如果它们的长度相同,试试这个:

import numpy as np
list1 = [1,2,3]
list2 = [1,5,9]
list3 = [2,4,1]
Root_List = [list1, list2,list3]
np.array(Root_List)

【讨论】:

    【解决方案2】:

    矩阵是列表的列表。

    最佳做法是首先定义您的根列表,然后附加您想要的子列表:

    Root_List = []
    list1 = [1, 2, 3]
    Root_List.append(list1)
    list2 = [1, 5, 9]
    Root_List.append(list2)
    list3 = [2, 4, 1]
    Root_List.append(list3)
    

    正如@Antonio Manrique 所建议的,您还可以使用 numpy 对其进行转换,以受益于该库的矩阵计算功能。 This answer answer how to convert a python list of list to a numpy matrix

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      • 2011-01-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多