python converting strings in list to ints and floats

人盡茶涼 提交于 2021-01-29 11:11:03

问题


If I were to have the following list:

lst = ['3', '7', 'foo', '2.6', 'bar', '8.9']

how would I convert all possible items into either ints or floats accordingly, to get

lst = [3, 7, 'foo', 2.6, 'bar', 8.9]

thanks in advance.


回答1:


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)

Output:

[3, 7, 'foo', 2.6, 'bar', 8.9]



回答2:


Try something like this :

lst = ['3', '7', 'foo', '2.6', 'bar', '8.9']

for j,i in enumerate(lst):
    if i.isdigit():
        lst[j]=int(i)
    elif '.' in i:
        lst[j]=float(i)

output:

[3, 7, 'foo', 2.6, 'bar', 8.9]


来源:https://stackoverflow.com/questions/48441382/python-converting-strings-in-list-to-ints-and-floats

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!