问题:将列表中的所有字符串转换为int

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

所以,如果我有:

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

我该如何做:

results = [1, 2, 3]

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:

results = [1, 2, 3]

回答 0

使用map功能(在Python 2.x中):

results = map(int, results)

在Python 3中,您需要将结果从map转换为列表:

results = list(map(int, results))

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))

回答 1

使用列表理解

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

例如

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

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]

回答 2

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

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

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。