简体   繁体   中英

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

I have 3 lists

> 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:

> mat=[a x_1 y_1]

like in MATLAB where a will be 1 column x_1 second column and y_1 third column.

> 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

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:

> c=[a,x_1,y_1]

How can I do this as well?

2D lists in python are different than in MATLAB!

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:

C = [A, B]

Then, C would be equal to [["red", "green", "blue"], ["orange", "yellow", "purple"]]

I could access elements of C such as:

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. You can just write,

mat = [x_1 y_1]

This list will be 2x10. You want to transpose this list, so you should be able to use zip to do:

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:

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

If you need a numpy array anyway, then:

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.

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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