To initialize a two-dimensional list in Python, use
t = [ [0]*3 for i in range(3)]
But don't use [[v]*n]*n, it is a trap!
>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0]=1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
Answer from Jason CHAN on Stack OverflowHow to initialize a two-dimensional array (list of lists, if not using NumPy) in Python? - Stack Overflow
Python - Conversion of list of arrays to 2D array - Stack Overflow
2D array of lists in python - Stack Overflow
Explain 2D Lists
To initialize a two-dimensional list in Python, use
t = [ [0]*3 for i in range(3)]
But don't use [[v]*n]*n, it is a trap!
>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0]=1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
A pattern that often came up in Python was
bar = []
for item in some_iterable:
bar.append(SOME EXPRESSION)
which helped motivate the introduction of list comprehensions, which convert that snippet to
bar = [SOME_EXPRESSION for item in some_iterable]
which is shorter and sometimes clearer. Usually, you get in the habit of recognizing these and often replacing loops with comprehensions.
Your code follows this pattern twice
twod_list = [] \
for i in range (0, 10): \
new = [] \ can be replaced } this too
for j in range (0, 10): } with a list /
new.append(foo) / comprehension /
twod_list.append(new) /
Not sure if I understood the question correctly, but does this work for you?
import numpy as np
A = [[1,2,3],[4,5,6],[7,8,9]]
A = np.array(A)
If A is a list of numpy array, how about this:
Ah = np.vstack(A)
Av = np.hstack(A)
If I understood correctly what you're asking, you have a case where numpy did not convert array of arrays into 2d array. This can happen when your arrays are not of the same size. Example:
Automatic conversion to 2d array:
import numpy as np
a = np.array([np.array([1,2,3]),np.array([2,3,4]),np.array([6,7,8])])
print a
Output:
>>>[[1 2 3]
[2 3 4]
[6 7 8]]
No automatic conversion (look for the change in the second subarray):
import numpy as np
b = np.array([np.array([1,2,3]),np.array([2,3,4,5]),np.array([6,7,8])])
print b
Output:
>>>[array([1, 2, 3]) array([2, 3, 4, 5]) array([6, 7, 8])]
I found a couple of ways of converting an array of arrays to 2d array. In any case you need to get rid of subarrays which have different size. So you will need a mask to select only "good" subarrays. Then you can use this mask with list comprehensions to recreate array, like this:
import numpy as np
a = np.array([np.array([1,2,3]),np.array([2,3,4,5]),np.array([6,7,8])])
mask = np.array([True, False, True])
c = np.array([element for (i,element) in enumerate(a) if mask[i]])
print a
print c
Output:
>>>>[array([1, 2, 3]) array([2, 3, 4, 5]) array([6, 7, 8])]
>>>>[[1 2 3]
[6 7 8]]
Or you can delete "bad" subarrays and use vstack(), like this:
import numpy as np
a = np.array([np.array([1,2,3]),np.array([2,3,4,5]),np.array([6,7,8])])
mask = np.array([True, False, True])
d = np.delete(a,np.where(mask==False))
e = np.vstack(d)
print a
print e
Output:
>>>>[array([1, 2, 3]) array([2, 3, 4, 5]) array([6, 7, 8])]
>>>>[[1 2 3]
[6 7 8]]
I believe second method would be faster for large arrays, but I haven't tested the timing.
Just as you wrote it:
>>> matrix = [["str1", "str2"], ["str3"], ["str4", "str5"]]
>>> matrix
[['str1', 'str2'], ['str3'], ['str4', 'str5']]
>>> matrix[0][1]
'str2'
>>> matrix[0][1] += "someText"
>>> matrix
[['str1', 'str2someText'], ['str3'], ['str4', 'str5']]
>>> matrix[0].extend(["str6"])
>>> matrix[0]
['str1', 'str2someText', 'str6']
Just think about 2D matrix as list of the lists. Other operations also work fine, for example,
>>> matrix[0].append('value')
>>> matrix[0]
[0, 0, 0, 0, 0, 'value']
>>> matrix[0].pop()
'value'
>>>
You can either do it with the basic:
matrix = [
[["s1","s2"], ["s3"]],
[["s4"], ["s5"]]
]
or you can do it very genericially
from collections import defaultdict
m = defaultdict(lambda : defaultdict(list))
m[0][0].append('s1')
In the defaultdict case you have a arbitrary matrix that you can use, any size and all the elements are arrays, to be manipulated accordingly.
Hi redditors!
I'm learning Python and I have to do a project with 2D lists. I'm fairly new to programming and I'm having a hard time understanding the format of a 2D list.
I'm trying to create rows and columns with '.' but I can only print out one row.....can someone help me by giving a simple example on how to do 2D lists, please? Oh, and reddit is my last resource. I have been looking for material I can understand but I'm having trouble :_(
You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this "list comprehension".
# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5
Matrix = [[0 for x in range(w)] for y in range(h)]
#You can now add items to the list:
Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range...
Matrix[0][6] = 3 # valid
Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index".
print Matrix[0][0] # prints 1
x, y = 0, 6
print Matrix[x][y] # prints 3; be careful with indexing!
Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.
If you really want a matrix, you might be better off using numpy. Matrix operations in numpy most often use an array type with two dimensions. There are many ways to create a new array; one of the most useful is the zeros function, which takes a shape parameter and returns an array of the given shape, with the values initialized to zero:
>>> import numpy
>>> numpy.zeros((5, 5))
array([[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0.]])
Here are some other ways to create 2-d arrays and matrices (with output removed for compactness):
numpy.arange(25).reshape((5, 5)) # create a 1-d range and reshape
numpy.array(range(25)).reshape((5, 5)) # pass a Python range and reshape
numpy.array([5] * 25).reshape((5, 5)) # pass a Python list and reshape
numpy.empty((5, 5)) # allocate, but don't initialize
numpy.ones((5, 5)) # initialize with ones
numpy provides a matrix type as well, but it is no longer recommended for any use, and may be removed from numpy in the future.
I have a list:
data=[1,2,3,4,5,6,7,...]
and I want to transform it into a 2-dimensional array, with 5 columns and 10 rows
How can I do it?
Hello, I have a simple question : For example, I have 3 lists a,b,c , and I want to join them into one big 2d array called d, how do I do it:
a= [1,2,3]
b= [4,5,6]
c= [7,8,9]
result wanted :
d= [
[1,2,3],
[4,5,6],
[7,8,9]
]
thank you !!!