Home > Enterprise >  Unpacking list in the list of foats and list
Unpacking list in the list of foats and list

Time:10-06

How to get from a list of floats and one list only one list of floats, please?

list = [1., 2., 4., [4., 5., 6.], 5.]

desired = [1., 2., 4., 4., 5., 6., 5.]

CodePudding user response:

One of the simplest ways would to be to loop through the list while checking for elements that are lists then treating them differently.

I thought there might be a cleverer solution but if there is then it is too clever for me to think of!

original = [1., 2., 4., [4., 5., 6.], 5.]
desired = []
for i in original:
    if isinstance(i, list):
        desired.extend(i)
    else:
        desired.append(i)

This only works when the depth of lists within a list is one, if you have lists within lists within lists then it won't work.

BTW: naming your list as "list" is not good practice as list is a keyword in Python, so I have renamed it to "original" in my code.

  • Related