如何将列表类型转换为Python中的浮动



我正在尝试将list数据类型转换为float。我尝试了遵循代码,但它不起作用,listf仍将数据类型显示为list

for x in range(0,5):
     timeVar.append((matchedLine4[x]).replace(stringToMatch4,'').rstrip())
     listf=map(float,timeVar)
     #list1 = [float(i) for i in timeVar]
     print(type(listf))

您通常不能将列表转换为浮点。但是,如果首先将字符串转换为float,然后添加到列表中,它将更容易,并且看起来像:

代码:

matchedLine4 = '1 2 3x 4 5.7'.split()
listf = []
stringToMatch4 = 'x'
for x in range(0, 5):
    timeVar = float(matchedLine4[x].replace(stringToMatch4, '').rstrip())
    listf.append(timeVar)
print(listf)

结果:

[1.0, 2.0, 3.0, 4.0, 5.7]

怎么样:

listf = list(map(float, timeVar))

最新更新