Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reducing a List of Lists

I have this pretty un-sightly list below of length 3:

[([('euw1', 12700)], [('la2', 1800)]), 
([('kr', 7500), ('br1', 4700), ('jp1', 400), ('sg2', 100)], [('vn2', 1200), ('oc1', 600)]), 
([('na1', 5400), ('eun1', 3900), ('la1', 2300), ('tr1', 900),('ph2', 200)], [('tw2', 700), ('ru', 400), ('th2', 100)])]

Ideally I would like my list to be flattened into the form:

[[('euw1', 12700), ('la2', 1800)], 
[('kr', 7500), ('br1', 4700), ('jp1', 400), ('sg2', 100),('vn2', 1200),('oc1', 600)], 
[('na1', 5400), ('eun1', 3900), ('la1', 2300), ('tr1', 900),('ph2', 200),('tw2', 700), ('ru', 400), ('th2', 100)]]

Does anybody know how I might go about this, ideally using as little packages as possible?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use more_itertools.flatten.

from more_itertools import flatten

lst = [
  ([('euw1', 12700)], [('la2', 1800)]), 
  ([('kr', 7500), ('br1', 4700), ('jp1', 400), ('sg2', 100)], [('vn2', 1200), ('oc1', 600)]), 
  ([('na1', 5400), ('eun1', 3900), ('la1', 2300), ('tr1', 900),('ph2', 200)], [('tw2', 700), ('ru', 400), ('th2', 100)])
]

[list(flatten(el)) for el in lst]

Output:

[[('euw1', 12700), ('la2', 1800)],
 [('kr', 7500),
  ('br1', 4700),
  ('jp1', 400),
  ('sg2', 100),
  ('vn2', 1200),
  ('oc1', 600)],
 [('na1', 5400),
  ('eun1', 3900),
  ('la1', 2300),
  ('tr1', 900),
  ('ph2', 200),
  ('tw2', 700),
  ('ru', 400),
  ('th2', 100)]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading