有时我们可以有一个包含字符串的列表,但是字符串本身是数字和右引号。在这样的列表中,我们希望将字符串元素转换为实际的整数。

用 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



版权声明:本文为weixin_33483080原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_33483080/article/details/113642409