将 Python 中列表中的所有字符串转换为整数


有时候,我们可能有一个包含字符串的列表,但字符串本身是数字和结束引号。在此类列表中,我们要将字符串元素转换为实际整数。

使用 int()

int 函数采用参数,并将其转换为整数(如果这些参数已经是数字)。因此,我们设计一个 for 循环来遍历列表中的每一个元素,并应用 in 函数。我们将最终结果存储在一个新列表中。

示例

 实时演示

listA = ['5', '2','-43', '23']
# Given list
print("Given list with strings : \n",listA)
# using int
res = [int(i) for i in listA]
# Result
print("The converted list with integers : \n",res)

输出

运行以上代码会得到以下结果 −

Given list with strings :
['5', '2', '-43', '23']
The converted list with integers :
[5, 2, -43, 23]

使用 map 和 list

map 函数可用于将 in 函数应用于给定列表中作为字符串存在的每个元素。

示例

 实时演示

listA = ['5', '2','-43', '23']
# Given list
print("Given list with strings : \n",listA)
# using map and int
res = list(map(int, listA))
# Result
print("The converted list with integers : \n",res)

输出

运行以上代码会得到以下结果 −

Given list with strings :
['5', '2', '-43', '23']
The converted list with integers :
[5, 2, -43, 23]

更新于: 2020 年 6 月 4 日

2 千次观看

启动你的 职业生涯

通过完成课程取得认证

开始学习
广告
© . All rights reserved.