在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函数可用于将int函数应用于给定列表中以字符串形式出现的每个元素。
示例
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]
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短