将字符串列表转换为Int或Float

Roh*_*hit 0 python list python-3.x

我的清单为:

list = ['67.50', '70.00', '72.50', '75.00', '77.50', '80.00', '82.50']
Run Code Online (Sandbox Code Playgroud)

我想检查字符串是否为foat,然后将其转换为float,如果字符串为int,则应将其转换为int。

所需输出:

list = [67.50, 70, 72.50, 75, 77.50, 80, 82.5]
Run Code Online (Sandbox Code Playgroud)

Chr*_*nds 5

您可以利用float.is_integer()

>>> lst = ['67.50', '70.00', '72.50', '75.00', '77.50', '80.00', '82.50']
>>> [int(x) if x.is_integer() else x for x in map(float, lst)]
[67.5, 70, 72.5, 75, 77.5, 80, 82.5]
Run Code Online (Sandbox Code Playgroud)