有时我们可以有一个包含字符串的列表,但是字符串本身是数字和右引号。在这样的列表中,我们希望将字符串元素转换为实际的整数。
用 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函数可用于将int函数应用于给定列表中以字符串形式出现的每个元素。
示例listA = [‘5’, ‘2’,’-43′, ’23’]
# Given list
print(“Given list with strings : \n”,listA)
# using map and int
res