How to convert a list of string to a list of int

后端 未结 4 2052
长情又很酷
长情又很酷 2021-01-26 04:59

I have this list in a list

a = [[\'1\',\'2\',\'3\',\'4\'],[\'1\',\'2\',\'3\',\'4\'],[\'1\',\'2\',\'3\',\'4\']]

but i need it to be ints , im

相关标签:
4条回答
  • 2021-01-26 05:50
    In [51]: a = [['1','2','3','4'],['1','2','3','4'],['1','2','3','4']]
    
    In [52]: [map(int, l) for l in a]
    Out[52]: [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
    
    0 讨论(0)
  • 2021-01-26 05:51

    You can use a nested list comprehension like so:

    a = [['1','2','3','4'],['1','2','3','4'],['1','2','3','4']]
    b = [ [int(j) for j in i] for i in a]
    
    0 讨论(0)
  • 2021-01-26 05:51

    Here's an idea:

    >>> a = [['1','2','3','4'],['1','2','3','4'],['1','2','3','4']]
    >>> map(lambda l: map(int, l), a)
    [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
    
    0 讨论(0)
  • 2021-01-26 05:53

    An example using nested list comprehension:

    In [1]: a = [['1','2','3','4'],['1','2','3','4'],['1','2','3','4']]
    
    In [2]: [[int(s) for s in l] for l in a]
    Out[2]: [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]
    
    0 讨论(0)
提交回复
热议问题