-2

I have this list:

fxrate = 
[[['9.6587'], ['9.9742'], ['9.9203'], ['10.1165'], ['10.1087']],
 [['10.7391'], ['10.8951'], ['11.1355'], ['11.561'], ['11.7873']],
 [['8.61'], ['8.9648'], ['9.0155'], ['9.153'], ['9.1475']]]

I would like to make a list like this by using Python:

[[9.6587, 9.9742, 9.9203, 10.1165, 10.1087],
 [10.7391, 10.8951, 11.1355, 11.561, 11.7873],
 [8.61, 8.9648, 9.0155, 9.153, 9.1475]]

Needless to say I'm fairly new to Python and programming in general. However all I end up with is either one list of values but not at three sets of lists

victor
  • 1

1 Answers1

0

What you want to do is flatten your list, Just use a list comprehension. This will take any list of lists you have and flatten it such that, Your list only has a depth of one. i.e. [["foo"], ["bar"],["List_of_lists"]] would become ["foo", "bar", "complex_lists"]

flat_list = [item for sublist in l for item in sublist]

As specified here

You can format this into your code as necessary. Like so:

fxrate = 
   [[['9.6587'], ['9.9742'], ['9.9203'], ['10.1165'], ['10.1087']],
   [['10.7391'], ['10.8951'], ['11.1355'], ['11.561'], ['11.7873']],
   [['8.61'], ['8.9648'], ['9.0155'], ['9.153'], ['9.1475']]]
flat_fxrate = [[item for sublist in fxrate[0] for item in sublist],[item for sublist in fxrate[1] for item in sublist],[item for sublist in fxrate[2] for item in sublist]]

For example. Since you want it split in three or if you plan to upscale it. Or to make it more legible, you can use a loop and append each part. Like so. Note: In general it's a lot better to use a loop because then no matter what the size of this list is, it will always work.

flat_fxrate = []
fxrate = 
   [[['9.6587'], ['9.9742'], ['9.9203'], ['10.1165'], ['10.1087']],
   [['10.7391'], ['10.8951'], ['11.1355'], ['11.561'], ['11.7873']],
   [['8.61'], ['8.9648'], ['9.0155'], ['9.153'], ['9.1475']]]
for x in fxrate:
    flat_fxrate.append([item for sublist in x for item in sublist])
Daemonique
  • 468
  • 2
  • 5
  • 15
  • Thanks! This was exactly what I wanted to do! I was not able to get it to work with the other solutions that was presented, but this did the trick! – victor Dec 02 '19 at 07:32