我想将矩阵转换为列表 python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4048792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:01:14  来源:igfitidea点击:

I want to convert a matrix to a list python

python

提问by Ghassen

Hi there I need to convert a matrix to a list as the example below

嗨,我需要将矩阵转换为列表,如下例所示

Matrix:
[[  1.   6.  13.  10.   2.]
 [  2.   9.  10.  13.  15.]
 [  3.  15.  13.  14.  16.]
 [  4.   5.  14.  13.   6.]
 [  5.  18.  16.   4.   3.]
 [  6.   7.  12.  18.   3.]
 [  7.   1.   8.  17.  11.]
 [  8.  14.   5.   4.  16.]
 [  9.  16.  18.  17.  15.]
 [ 10.   8.   9.  15.  17.]
 [ 11.  11.  17.  18.  12.]]

List:
[(1, 6, 13, 10, 2),  (2, 9, 10, 13, 15), (3, 15, 13, 14, 16),
 (4, 5, 14, 13, 6),  (5, 18, 16, 4, 3),  (6, 7, 12, 18, 3), 
 (7, 1, 8, 17, 11),  (8, 14, 5, 4, 16),  (9, 16, 18, 17, 15),
 (10, 8, 9, 15, 17), (11, 11, 17, 18, 12)]

Thx in adavance

提前谢谢

回答by aaronasterling

The best way to do it is:

最好的方法是:

result = map(tuple, Matrix)

回答by Joe Kington

Is this a numpy matrix? If so, just use the tolist()method. E.g.:

这是一个numpy矩阵吗?如果是这样,只需使用该tolist()方法。例如:

import numpy as np
x = np.matrix([[1,2,3],
               [7,1,3],
               [9,4,3]])
y = x.tolist()

This yields:

这产生:

y --> [[1, 2, 3], [7, 1, 3], [9, 4, 3]]

回答by fabrizioM

if you are using numpy and you want to just traverse the matrix as a list then you can just

如果您使用的是 numpy 并且只想将矩阵作为列表遍历,那么您可以

from numpy import array
m = [[  1.   6.  13.  10.   2.]
 [  2.   9.  10.  13.  15.]
 [  3.  15.  13.  14.  16.]
 [  4.   5.  14.  13.   6.]
 [  5.  18.  16.   4.   3.]
 [  6.   7.  12.  18.   3.]
 [  7.   1.   8.  17.  11.]
 [  8.  14.   5.   4.  16.]
 [  9.  16.  18.  17.  15.]
 [ 10.   8.   9.  15.  17.]
 [ 11.  11.  17.  18.  12.]]

for x in array(m).flat:
   print x

This will not consume extra memory

这不会消耗额外的内存

回答by Walid Bousseta

OR you can use one of those :

或者您可以使用其中之一:

1- li = list(i for j in yourMatrix for i in j)
2- li = sum(yourMatrix, [])