Convert all strings in a list to int

前端 未结 4 723
夕颜
夕颜 2020-11-22 01:49

In Python, I want to convert all strings in a list to integers.

So if I have:

results = [\'1\', \'2\', \'3\']

How do I make it:

相关标签:
4条回答
  • 2020-11-22 02:08

    Use a list comprehension:

    results = [int(i) for i in results]
    

    e.g.

    >>> results = ["1", "2", "3"]
    >>> results = [int(i) for i in results]
    >>> results
    [1, 2, 3]
    
    0 讨论(0)
  • 2020-11-22 02:09

    Here is a simple solution with explanation for your query.

     a=['1','2','3','4','5'] #The integer represented as a string in this list
     b=[] #Fresh list
     for i in a: #Declaring variable (i) as an item in the list (a).
         b.append(int(i)) #Look below for explanation
     print(b)
    

    Here, append() is used to add items ( i.e integer version of string (i) in this program ) to the end of the list (b).

    Note: int() is a function that helps to convert an integer in the form of string, back to its integer form.

    Output console:

    [1, 2, 3, 4, 5]
    

    So, we can convert the string items in the list to an integer only if the given string is entirely composed of numbers or else an error will be generated.

    0 讨论(0)
  • 2020-11-22 02:23

    A little bit more expanded than list comprehension but likewise useful:

    def str_list_to_int_list(str_list):
        n = 0
        while n < len(str_list):
            str_list[n] = int(str_list[n])
            n += 1
        return(str_list)
    

    e.g.

    >>> results = ["1", "2", "3"]
    >>> str_list_to_int_list(results)
    [1, 2, 3]
    

    Also:

    def str_list_to_int_list(str_list):
        int_list = [int(n) for n in str_list]
        return int_list
    
    0 讨论(0)
  • 2020-11-22 02:30

    Use the map function (in Python 2.x):

    results = map(int, results)
    

    In Python 3, you will need to convert the result from map to a list:

    results = list(map(int, results))
    
    0 讨论(0)
提交回复
热议问题