简体   繁体   English

如何将元组中的一些项从列表转换为浮点数?

[英]How to convert some items in a tuple from list to float?

Due to some slicing I did previously in my script I ended up with a huge tuple that looks like this: 由于我之前在我的脚本中做了一些切片,我最终得到了一个巨大的元组,如下所示:

(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, [102.37], [129.6], [190.64], [181.98], [192.79])

In the example above the first 7 items are floats and the other are lists containing one element each, which are also floats. 在上面的示例中,前7个项目是浮点数,另一个是包含每个元素的列表,这些列表也是浮点数。

I would like to get rid of the lists and keep floats so I can add up all the values to calculate the average stock price by 6 month period. 我想摆脱列表并保留浮点数,以便我可以将所有值相加以计算6个月期间的平均股票价格。

What is the most pythonic way to achieve this? 实现这一目标的最pythonic方法是什么?

This function returns a float whether it is given a float or a list: 无论是浮点还是列表,此函数都会返回float:

def delistify(x):
    try:
        return x[0]
    except TypeError:
        return x

If you need the output to be a tuple, you can use it like: 如果您需要输出为元组,则可以使用它:

print tuple( delistify(x) for x in my_list )

Or, if a list is also ok, the most pythonic is a list comprehension: 或者,如果列表也可以,最pythonic是列表理解:

print [ delistify(x) for x in my_list ]

If you want to extract the numbers from the lists: 如果要从列表中提取数字:

In [1]: t = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, [102.37], [129.6], [190.64], [181.98], [192.79])
In [2]: tuple(tt if isinstance(tt, float) else tt[0] for tt in t)
Out[2]: (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 102.37, 129.6, 190.64, 181.98, 192.79)

If you want to "get rid of" the lists: 如果你想“摆脱”这些清单:

In [3]: tuple(tt for tt in t if isinstance(tt, float))
Out[3]: (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM