Convert all strings to list in int

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

So if I have:

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

How should I do it:

results = [1, 2, 3]
+529
source share
4 answers

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

results = map(int, results)

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

results = list(map(int, results))
+1045
source

Use a list comprehension :

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

eg

>>> results = ["1", "2", "3"]
>>> results = [int(i) for i in results]
>>> results
[1, 2, 3]
+348
source

A bit more advanced than list comprehension, but also 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)

eg

>>> 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
+1
source

How can I change the list below to a list of numbers?

answer = [[1, 10], [7, 3]] answer = [1, 10, 7, 3]

0
source

All Articles