本文介绍了python将列表中的字符串转换为int和float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果要提供以下列表:
lst = ['3', '7', 'foo', '2.6', 'bar', '8.9']
我将如何将所有可能的项目相应地转换为int或float以获得
how would I convert all possible items into either ints or floats accordingly, to get
lst = [3, 7, 'foo', 2.6, 'bar', 8.9]
提前谢谢.
推荐答案
环顾每个项目并尝试进行转换.如果转换失败,则说明它不可转换.
Loop over each item and make an attempt to convert. If the conversion fail then you know it's not convertible.
def tryconvert(s):
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
return s
lst = ['3', '7', 'foo', '2.6', 'bar', '8.9']
newlst = [tryconvert(i) for i in lst]
print(newlst)
输出:
[3, 7, 'foo', 2.6, 'bar', 8.9]
这篇关于python将列表中的字符串转换为int和float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!