更新时间:2022-06-01 14:40:06
环顾每个项目并尝试进行转换.如果转换失败,则说明它不可转换.
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]