简体   繁体   中英

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.

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.

What is the most pythonic way to achieve this?

This function returns a float whether it is given a float or a list:

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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