How to convert list of intable strings to int

前端 未结 6 1358
我在风中等你
我在风中等你 2020-12-06 13:28

In Python, I want to convert a list of strings:

l = [\'sam\',\'1\',\'dad\',\'21\']

and convert the integers to integer types like this:

6条回答
  •  無奈伤痛
    2020-12-06 13:52

    • Use a list comprehension to validate the numeracy of each list item.
    • str.isnumeric won't pass a negative sign
      • Use str.lstrip to remove the -, check .isnumeric, and convert to int if it is.
      • Alternatively, use str.isdigit in place of .isnumeric.

    Keep all values in the list

    l = ['sam', '1', 'dad', '21', '-10']
    
    t = [int(v) if v.lstrip('-').isnumeric() else v for v in l]
    
    print(t)
    
    >>> ['sam', 1, 'dad', 21, -10]
    

    Remove non-numeric values

    l = ['sam', '1', 'dad', '21', '-10']
    
    t = [int(v) for v in t if v.lstrip('-').isnumeric()]
    
    print(t)
    
    >>> [1, 21, -10]
    

    Nested list

    l = [['aa', '2'], ['bb', '3'], ['sam', '1', 'dad', '21', '-10']]
    
    t = [[int(v) if v.lstrip('-').isnumeric() else v for v in x] for x in l]
    
    print(t)
    
    >>> [['aa', 2], ['bb', 3], ['sam', 1, 'dad', 21, -10]]
    

提交回复
热议问题