将一个列表中的所有字符串转换为int

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

因此,如果我有

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

我怎样才能使它。

results = [1, 2, 3]
对该问题的评论 (1)
解决办法

使用 map 函数 (在Python 2.x中)。

results = map(int, results)

在Python 3中,你需要将 map 的结果转换为一个列表。

results = list(map(int, results))
评论(3)

使用列表理解

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

例如

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

比起清单理解力来说,扩展了一点,但同样也很有用。

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)

例如

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

另外。

def str_list_to_int_list(str_list):
    int_list = [int(n) for n in str_list]
    return int_list
评论(0)