Reputation: 73
I got the following list of lists:
mat = [['a,p,p,l,e'], ['a,g,o,d,o'], ['n,n,e,r,t'], ['g,a,T,A,C'], ['m,i,c,s,r'], ['P,o,P,o,P']]
As you can see, this list of lists doesn't function as a matrix properly.
How can I convert it to:
mat = [['a','p','p','l','e'], ['a','g','o','d','o'], ['n','n','e','r','t'], ['g','a','T','A','C'], ['m','i','c','s','r'], ['P','o','P','o','P']]
such that if i operate mat[1][2]
i get o
Upvotes: 0
Views: 331
Reputation: 422
Here is a way to do it with list comprehension:
If we have a nested list like your example.
nested_list = [['a,p,p,l,e'], ['a,g,o,d,o'], ['n,n,e,r,t'], ['g,a,T,A,C'], ['m,i,c,s,r'], ['P,o,P,o,P']]
We would have to go through each item and split every item's string on the ",
" so ['a, p, p, l, e']
would be ['a', 'p', 'p', 'l', 'e']
.
# New list
matrix = [item.split(",") for sublist in nested_list for item in sublist]
print(matrix)
The result will now be a matrix.
[['a', 'p', 'p', 'l', 'e'],
['a', 'g', 'o', 'd', 'o'],
['n', 'n', 'e', 'r', 't'],
['g', 'a', 'T', 'A', 'C'],
['m', 'i', 'c', 's', 'r'],
['P', 'o', 'P', 'o', 'P']]
This is the same as writing this:
matrix = []
for item in nested_list:
for i in item:
matrix.append(i.split(","))
print(matrix)
Have a look at this link about nested list comprehension
Upvotes: 2
Reputation: 1
You could use something like this to convert it:
mat = [['a,p,p,l,e'], ['a,g,o,d,o'], ['n,n,e,r,t'], ['g,a,T,A,C'], ['m,i,c,s,r'], ['P,o,P,o,P'
newMat = []
for i in mat:
newMat.append(i[0].split(","))
print(newMat[1][2])
Upvotes: 0