How To Convert A Matrix Of Strings Into A Matrix Of Integers Using Comprehensions
I have a matrix [['1', '2'], ['3', '4']] which I want to convert to a matrix of integers. Is there is a way to do it using comprehensions?
Solution 1:
[ [int(a), int(b)] for a, b in matrix ]
Solution 2:
In the general case:
int_matrix = [[int(column) forcolumninrow] forrowin matrix]
Solution 3:
You could do it like:
>>>test = [['1', '2'], ['3', '4']]>>>[[int(itemInner) for itemInner in itemOuter] for itemOuter in test]
[[1, 2], [3, 4]]
As long as all the items are integer, the code could work.
Hope it be helpful!
Solution 4:
[map(int, thing) for thing in matrix]
Post a Comment for "How To Convert A Matrix Of Strings Into A Matrix Of Integers Using Comprehensions"