Convert list to matrix (python)
Solution 1
This can be done very easily:
def list_to_matrix(lst):
return [lst]
Usage:
>>> lst = [1,2,3,4]
>>> lst = list_to_matrix(lst)
>>> lst
[[1,2,3,4]]
If we have cases where we might get things that are already in list-of-list form, we can add a little more robustness by doing this:
from collections import Iterable
def list_to_matrix(lst):
if lst:
return lst if all(isinstance(item, Iterable) and not isinstance(item, str) for item in lst) else [lst]
else:
# returns empty matrix if input list was empty
return [[]]
Note that this method is pretty fragile, but at least allows you to safely pass either a base list or a list of list form blindly and get back the correct thing.
Solution 2
Do you mean this (a matrix as a list of lists):
In [1]: matrix = [[1,2,3]]
In [2]: matrix
Out[2]: [[1, 2, 3]]
In [3]: matrix.append([4,5,6])
In [4]: matrix
Out[4]: [[1, 2, 3], [4, 5, 6]]
Solution 3
This works for any objects in list. It gives to every object its coordinates in pseudo 2d list:
def to_matrix(l, n):
return [(x[0] / n, x[0] % n , x) for x in l]
The output for to_matrix([objects], 3)
would be:
[(0, 0, some_object),
(0, 1, some_object),
(0, 2, some_object),
(1, 0, some_object),
(1, 1, some_object),
(1, 2, some_object),
(2, 0, some_object),
(2, 1, some_object),
(2, 2, some_object)]
If you need a real 2d array, this code will do the job:
def toMatrix(l, n):
matrix = []
for i in range (0, len(l), n):
matrix.append(l[i:i+n])
return matrix
SecondLemon
Updated on September 04, 2020Comments
-
SecondLemon over 3 years
I would like to convert a list to a matrix so that I can use the .append function the way I need it.
list = ["1", "2", "3"]
should become[["1", "2", "3"]]
.Then when I use
list.append(["4", "5", "6"])
it will become[["1", "2", "3"], ["4", "5", "6"]]
instead of["1", "2", "3", ["4", "5", "6"]]
.How can I do this?
-
itzMEonTV about 9 years
list =[ ["1", "2", "3"]]
, then you can append lists. likelist.append(["4", "5", "6"])
which gives you expected result -
SecondLemon about 9 yearsThanks got it. Tried this myself in the json.dump([list],file) but it didn't work here (which I understand now). Simply added a definition (list2 = [list] before the son.dump and now it works. Thank!
-
itzMEonTV about 9 yearsno need to create new
list2
. Simplylist = [list]
and then you can append.
-
-
SecondLemon about 9 yearsWell I can't change my 'list'. I get a huge list every 30 min via my code and wish to append it. I check if the file is empty or not so it can first print a list and then use the append function to add further list resulting in a matrix.
-
Ramces Gonzalez almost 3 yearsthanks so much, this helped me solve my issue of converting a 100 item list into a matrix of 10x10, now i'm going to see how to convert this matrix into a gray-scale image