在Python中如何将数字转换为浮在混合列表中 [英] in Python how to convert number to float in a mixed list
问题描述
我有一个像这样的字符串列表
I have a list of strings in the form like
a = ['str','5','','4.1']
我想将列表中的所有数字转换为浮点数,但其余部分保持不变
I want to convert all numbers in the list to float, but leave the rest unchanged, like this
a = ['str',5,'',4.1]
我尝试了
map(float,a)
但显然它给了我一个错误,因为某些字符串无法转换为浮点型.我也尝试过
but apparently it gave me an error because some string cannot be converted to float. I also tried
a[:] = [float(x) for x in a if x.isdigit()]
但这只会给我
[5]
,所以浮点数和所有其他字符串都丢失了.我该怎么做才能同时保留字符串和数字?
so the float number and all other strings are lost. What should I do to keep the string and number at the same time?
推荐答案
for i, x in enumerate(a):
try:
a[i] = float(x)
except ValueError:
pass
这假设您要更改a
,要创建新列表,可以使用以下命令:
This assumes you want to change a
in place, for creating a new list you can use the following:
new_a = []
for x in a:
try:
new_a.append(float(x))
except ValueError:
new_a.append(x)
这种try/except方法是标准的 EAFP ,并且还会更多比检查每个字符串是否为有效浮点数更有效,更不易出错.
This try/except approach is standard EAFP and will be more efficient and less error prone than checking to see if each string is a valid float.
这篇关于在Python中如何将数字转换为浮在混合列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!