关于python:将列表中的所有字符串转换为int

Convert all strings in a list to int

在Python中,我想将列表中的所有字符串转换为整数。

如果我有:

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

如何做到:

1
results = [1, 2, 3]


使用map函数(在python 2.x中):

1
results = map(int, results)

在python3中,您需要将来自map的结果转换为一个列表:

1
results = list(map(int, results))


使用列表理解:

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

例如

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


比列表理解稍微扩展一点,但同样有用:

1
2
3
4
5
6
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)

例如

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

也:

1
2
3
def str_list_to_int_list(str_list):
    int_list = [int(n) for n in str_list]
    return int_list

有很多不同的方法可以做到:

1)使用地图:

1
2
3
4
5
6
7
8
def toInt(string):
    return int(string)


equation = ["10","11","12"]
equation = map(toInt, equation)
for i in equation:
    print(type(i), i)

2)不使用map()进行操作

1
2
3
4
5
6
7
equation = ["10","11","12"]
new_list = []
for i in equation:
    new_list.append(int(i))

equation = new_list
print(equation)

有很多方法可以做到……