KaDeK970123
KaDeK970123

Reputation: 31

Make a matrix out of a list of sequences in python

I would like to make a matrix out of a list of sequences, an example could be:

list = ['101023', '101011', '102010', '102931']

Now I want to obtain a matrix like:

matrix = [[1, 0, 1, 0, 2, 3], [1, 0, 1, 0, 1, 1], [1, 0, 2, 0, 1, 0], [1, 0, 2, 9, 3, 1]]

Is there an efficient way to do this for bigger lists?

Upvotes: 0

Views: 477

Answers (2)

J. Dykstra
J. Dykstra

Reputation: 211

First, never name your list "list". List is a function in python that can be called. Also, I think you should look into numpy when dealing with arrays. But if you don't want to do that, then here is some code that should be efficient to create the output you desire.

list1 = ['101023', '101011', '102010', '102931']

list2 = []
for x in list1:
    t=list(x)
    list2.append(t)
print(list2)
[['1', '0', '1', '0', '2', '3'], ['1', '0', '1', '0', '1', '1'], ['1', '0', '2', '0', '1', '0'], ['1', '0', '2', '9', '3', '1']]

Upvotes: 0

slider
slider

Reputation: 12990

You can use a list comprehension where each element is a list of ints constructed from sequence strings in the main list:

lst = ['101023', '101011', '102010', '102931']
matrix = [[int(c) for c in seq] for seq in lst]

print(matrix)
# [[1, 0, 1, 0, 2, 3], [1, 0, 1, 0, 1, 1], [1, 0, 2, 0, 1, 0], [1, 0, 2, 9, 3, 1]]

Upvotes: 1

Related Questions