【问题标题】:Convert strings in list to floats and remove None? [duplicate]将列表中的字符串转换为浮点数并删除 None? [复制]
【发布时间】:2020-10-10 02:43:52
【问题描述】:
#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]

另外,如果列表中还包含“无”,我该怎么办?

【问题讨论】:

  • 那些不是floats,不是ints?
  • 对不起,它们是花车,是的
  • 您想保留Nones,还是删除它们?
  • 实际消除它们
  • 哇哦,谢谢!

标签: python list dictionary integer nonetype


【解决方案1】:

列表推导是最简单的方法:

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]

【讨论】:

  • 我不一定需要尾随的 0 哈哈,非常感谢 Sam!
【解决方案2】:

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

做花车:

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]

【讨论】:

  • 浮点数是数字,可以用不同的方式表示为字符串。但我仍然认为听起来你会更喜欢小数,所以我会添加这个来回答。
  • 非常高兴,安德鲁!谢天谢地,我的期权合约的出价计算到小数点后第二位哈哈!
  • 别担心,我也从事交易,但我从事外汇交易,我们的价格高达千分之一美分。尽管如此,我最终还是基于小数而不是浮点数为外汇编写了价格类。但是有一个小数包的学习曲线。 github.com/aallaire/python_forex_types/blob/master/forex_types/…
  • 一定会去看看的!
  • 它只适用于外汇交易。对股票没有帮助。它实际上还没有那么好.. 编辑:但它可以作为如何使用小数等的一个例子。
【解决方案3】:

您可以使用列表推导:

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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-26
    • 2011-11-25
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 2019-10-31
    相关资源
    最近更新 更多