[英]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]
I tried 我试过了
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()]
but it only gives me 但它只给了我
[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?
我该怎么做才能同时保留字符串和数字?
>>> a = ['str','5','','4.1']
>>> a2 = []
>>> for s in a:
... try:
... a2.append(float(s))
... except ValueError:
... a2.append(s)
>>> a2
['str', 5.0, '', 4.0999999999999996]
If you're doing decimal math, you may want to look at the decimal module: 如果您正在进行十进制数学运算,您可能需要查看十进制模块:
>>> import decimal
>>> for s in a:
... try:
... a2.append(decimal.Decimal(s))
... except decimal.InvalidOperation:
... a2.append(s)
>>> a2
['str', Decimal('5'), '', Decimal('4.1')]
for i, x in enumerate(a):
try:
a[i] = float(x)
except ValueError:
pass
This assumes you want to change a
in place, for creating a new list you can use the following: 这是假设你想改变
a
到位,用于创建您可以使用下面的一个新的列表:
new_a = []
for x in a:
try:
new_a.append(float(x))
except ValueError:
new_a.append(x)
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. 这种try / except方法是标准EAFP ,并且比检查每个字符串是否为有效浮点数更有效且更不容易出错。
Here's a way to do it without exception handling and using a bit of regex : - 这是一种无需异常处理和使用一些正则表达式的方法 : -
>>> a = ['str','5','','4.1']
>>> import re
>>> [float(x) if re.match("[+-]?(?:\d+(?:\.\d+)?|\.\d+)$", x) else x for x in a]
4: ['str', 5.0, '', 4.1]
Note that, this regex will cover only a basic range of numbers, applicable in your case. 请注意,此正则表达式仅涵盖基本范围的数字,适用于您的情况。 For more elaborate regex to match a wider range of floating-point numbers, like, including exponents, you can take a look at this question: -
对于更精细的正则表达式来匹配更广泛的浮点数,比如包括指数,你可以看一下这个问题: -
My version: 我的版本:
def convert(value):
try:
return float(value)
except ValueError:
return value
map(convert, a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.