将列表中的所有字符串转换为int[复制]

时间:2022-02-26 20:48:26

Possible Duplicate:
How to convert strings into integers in python?
How to convert a string list into an integer in python

可能的重复:如何在python中将字符串转换为整数?如何在python中将字符串列表转换为整数

In python, I want to convert all strings in a list to ints.

在python中,我希望将列表中的所有字符串转换为int。

So if I have:

所以如果我有:

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

How do I make it:

我该怎么做:

results = [1, 2, 3]

2 个解决方案

#1


768  

Use the map function(in py2):

使用map函数(在py2中):

results = map(int, results)

In py3:

在py3:

results = list(map(int, results))

#2


233  

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]

#1


768  

Use the map function(in py2):

使用map函数(在py2中):

results = map(int, results)

In py3:

在py3:

results = list(map(int, results))

#2


233  

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]