简体   繁体   中英

Python: an elegant way to extract floats from list?

Is there a more elegant way to do this?

I have a "double" list of the form:

rlist = [([-0.5753647], [1.3716470]), ([-0.57536478], [0.75418190]), ([-1.37632438], [0.57068748])]

from which I want to extract individual floating point numbers, formatted.

At the moment I'm using:

first_number = round(float(str(rlist[0][0]).strip('[]')),4)

for example, to get the first number. This is rather ugly. Is there a more succinct way to do it (in Python)?

DN

You can try something like this:

from itertools import chain
[round(x, 4) for x in chain(*chain(*rlist))]

itertools.chain can be used to flatten nested iterables. After that you can use list comprehension and round to obtain list of numbers with required precision.

If you are opting for itertools.chain() , if level of nesting is more please see the comments below this answer by @zero323

And round() has also some restrictions too,

f = -0.5753647

print f

-0.57536469999999995

print round(f, 4)

-0.57540000000000002

So,

rlist = [([-0.5753647], [1.3716470]),
     ([-0.57536478], [0.75418190]),
     ([-1.37632438], [0.57068748])]

def flatten(container):

    for i in container:
        if isinstance(i, list) or isinstance(i, tuple):
            for j in flatten(i):
                yield j
        else:
            yield i

print ["{0:.4f}".format(ele) for ele in list(flatten(rlist))]

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