How to convert a matrix of strings into a matrix of integers using comprehensions

后端 未结 4 639
甜味超标
甜味超标 2021-01-29 03:42

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条回答
  • 2021-01-29 04:14

    In the general case:

    int_matrix = [[int(column) for column in row] for row in matrix]
    
    0 讨论(0)
  • 2021-01-29 04:14
       [map(int, thing) for thing in matrix]
    
    0 讨论(0)
  • 2021-01-29 04:19

    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!

    0 讨论(0)
  • 2021-01-29 04:20
    [ [int(a), int(b)] for a, b in matrix ]
    
    0 讨论(0)
提交回复
热议问题