将列表中的字符串转换为浮点数并删除 None?

Convert strings in list to floats and remove None?

#search for option given symbol and expiration date 
list_of_dicts = 
r.options.find_options_for_stock_by_expiration(symbol,expirationDate,optionType='put')
print(list_of_dicts)



#convert list of dictionaries into single list by parameter given
parameter_a = 'bid_price'
new_list = [f[parameter_a] for f in list_of_dicts]
print(new_list)

将字典列表 (list_of_dicts) 转换为单个列表后,我得到了出价字符串列表:

['7.800000', '6.300000', '6.800000', '7.300000', '0.000000', '0.000000', '0.000000', '0.000000']

我的问题是,如何将这个字符串列表转换为浮点数列表? 基本上我需要看到的是这样的:

[7.800000, 6.300000, 6.800000, 7.300000, 0.000000, 0.000000, 0.000000, 0.000000]

还有,如果列表中也有'None'怎么办?

您可能不想将它们四舍五入到最接近的美元,因此您希望它们是浮点数或小数而不是整数(除非您可能希望将它们转换为便士数而不是美元数) .

要做花车:

new_list = [float(f[parameter_a]) for f in list_of_dicts]

做小数:

from decimal import Decimal
penny = Decimal(".01")
...
new_list = [Decimal(f[parameter_a]).quantize(penny) for f in list_of_dicts]

列表理解是最简单的方法:

new_list = ['7.800000', '6.300000', '6.800000', '7.300000', '0.000000', '0.000000', None, '0.000000']
float_list = [float(item) if item is not None else None for item in new_list ]
>>> print(new_list)
>>> print(float_list)
['7.800000', '6.300000', '6.800000', '7.300000', '0.000000', '0.000000', None, '0.000000']
[7.8, 6.3, 6.8, 7.3, 0.0, 0.0, None, 0.0]

您可以使用列表理解:

new_list = ['7.800000', '6.300000', '6.800000', '7.300000', '0.000000', '0.000000', None, '0.000000']
float_list = [float(item) for item in new_list if item]

print(new_list)
print(float_list)

输出:

['7.800000', '6.300000', '6.800000', '7.300000', '0.000000', '0.000000', None, '0.000000']
[7.8, 6.3, 6.8, 7.3, 0.0, 0.0, 0.0]