在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 女儿升学宴祝福语简短