python将列表中的字符串转换为整数和浮点数

0 python string int list

如果我有以下列表:

lst = ['3', '7', 'foo', '2.6', 'bar', '8.9']
Run Code Online (Sandbox Code Playgroud)

如何将所有可能的项目转换为int或者浮点数,以获得

lst = [3, 7, 'foo', 2.6, 'bar', 8.9]
Run Code Online (Sandbox Code Playgroud)

提前致谢.

iBu*_*Bug 7

循环遍历每个项目并尝试转换.如果转换失败,那么您就知道它不可转换.

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)
Run Code Online (Sandbox Code Playgroud)

输出:

[3, 7, 'foo', 2.6, 'bar', 8.9]
Run Code Online (Sandbox Code Playgroud)