简体   繁体   English

如何从python中的列表创建矩阵或二维列表?

[英]How to create matrix or 2d list from lists in python?

I have 3 lists 我有3个清单

> a= ones((10,1))
> 
> 
>  x_1=[1,2,3,4...,10] (i.e. list of 10 elements)
> 
>  y_1=[2,1,4,7,2,..20] (list of 10 elements)

I want to join these 3 list and make it as 2d list or matrix as: 我想加入这3个列表,使其成为2d列表或矩阵,如下所示:

> mat=[a x_1 y_1]

like in MATLAB where a will be 1 column x_1 second column and y_1 third column. 就像在MATLAB中,其中a将是1列x_1第二列和y_1第三列。

> mat= [[1,1,2],[1,2,1],[1,3,4],[]......[]]

I tried 我试过了

> np.matrix([[a,[[i] for i in x_1],[[i] for i in y_1]]])

but it gave an error as matrix must be 2 dimensionl 但是它给出了一个错误,因为矩阵必须是2维

How can I do this ? 我怎样才能做到这一点 ?

Also, if I have 2D arrays ie 另外,如果我有二维数组

>  a=np.ones((3,2))
> 
> x_1=[[1,2],[2,3],[2,4]]
> 
> y_1=[[3,4],[5,6],[3,4]]

Then how can I concatenate these arrays and make it as 然后我如何连接这些数组,并使其成为

> c=[[1,1,2,3,4],[1,2,3,5,6],[1,2,4,3,4]]

In matlab it is written as: 在matlab中,它写为:

> c=[a,x_1,y_1]

How can I do this as well? 我也该怎么做?

2D lists in python are different than in MATLAB! python中的2D列表与MATLAB中的2D列表不同!

If I have two lists 如果我有两个清单

A = ["red", "green", "blue"]
B = ["orange", "yellow", "purple"]

And I wanted to create a 2D list out of these two, I could just write: 我想从这两个列表中创建一个2D列表,我可以这样写:

C = [A, B]

Then, C would be equal to [["red", "green", "blue"], ["orange", "yellow", "purple"]] 然后,C等于[[“红色”,“绿色”,“蓝色”],[“橙色”,“黄色”,“紫色”]]

I could access elements of C such as: 我可以访问C的元素,例如:

C[0][1]
>> "red"
C[1][2]
>> "purple"
C[0]
>> ["red", "green", "blue"]

To answer your specific question, you have lists x_1 and y_1, and you want to create mat, a 2D list containing x_1 and y_1. 为了回答您的特定问题,您具有列表x_1和y_1,并且要创建一个包含x_1和y_1的二维列表。 You can just write, 你可以写

mat = [x_1 y_1]

This list will be 2x10. 此列表将为2x10。 You want to transpose this list, so you should be able to use zip to do: 您想转置此列表,因此您应该可以使用zip来执行以下操作:

mat = map(list, zip(*mat))

If you want to stay within "standard" Python (no numpy ), then to get a transposed 2D list you could do the following: 如果要保留在“标准” Python(无numpy )中, numpy获取转置的2D列表,可以执行以下操作:

mat = [p for p in zip(a, x_1, y_1)]

If you need a numpy array anyway, then: 如果仍然需要一个numpy数组,则:

import numpy as np
mat = np.array([a, x_1, y_1]).T

NOTE: in the above example replace np.array with np.matrix if that is what you want. 注意:在上面的示例中,如果需要, np.arraynp.matrix替换np.array

If your a array is a 2D array such as, eg, np.ones((10,1)) or np.ones((10,3)) then you can use one of the *stack() functions in numpy : 如果您a数组是2D数组,例如np.ones((10,1))np.ones((10,3))则可以在numpy使用* stack()函数之一:

mat = np.vstack([np.asarray(a).T, x_1, y_1]).T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM