Home > OS >  Reducing a List of Lists
Reducing a List of Lists

Time:01-27

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?

CodePudding user response:

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)]]
  • Related