在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 婆婆高寿祝福语大全简短