0

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?

4 Answers4

2
[ [int(a), int(b)] for a, b in matrix ]
user590028
  • 11,364
  • 3
  • 40
  • 57
2

In the general case:

int_matrix = [[int(column) for column in row] for row in matrix]
aruisdante
  • 8,875
  • 2
  • 30
  • 37
1

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!

Sheng
  • 3,467
  • 1
  • 17
  • 21
0
   [map(int, thing) for thing in matrix]
wwii
  • 23,232
  • 7
  • 37
  • 77