0

How can I remove the outer layer of this?

[[['SKU', 'DHF', 'KSD'], ['KUD', 'HFK', 'SDJ'], ['UDH', 'FKS', 'DJH']],
 [['KUG', 'UJY', 'FUY'], ['UGU', 'JYF', 'UYF'], ['GUJ', 'YFU', 'YFG']]]

There are plenty of posts detailing how to flatten a list of lists (essentially the same as removing the outer layer), but I could not find anything for a list of lists of lists

Thanks!

Jack Arnestad
  • 1,845
  • 13
  • 26
  • 1
    `[j for i in x for j in i]`, if `x` is the name of your list. Gives you `[['SKU', 'DHF', 'KSD'], ['KUD', 'HFK', 'SDJ'], ['UDH', 'FKS', 'DJH'], ['KUG', 'UJY', 'FUY'], ['UGU', 'JYF', 'UYF'], ['GUJ', 'YFU', 'YFG']]` – user3483203 May 14 '18 at 17:21
  • If that is *not* what you want, and you want a `1D` list, you could use the answers found in https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists – user3483203 May 14 '18 at 17:24
  • 1
    First answer is perfect! Thanks! – Jack Arnestad May 14 '18 at 17:24
  • Then the inner layer of the list of lists of lists is essentially irrelevant; you can use the same flatten-one-layer techniques as for a list of lists of anything else. – user2357112 May 14 '18 at 17:47

1 Answers1

1

To remove one layer, simply apply chain.from_iterable:

>>> items = [
...     [['SKU', 'DHF', 'KSD'], ['KUD', 'HFK', 'SDJ'], ['UDH', 'FKS', 'DJH']],
...     [['KUG', 'UJY', 'FUY'], ['UGU', 'JYF', 'UYF'], ['GUJ', 'YFU', 'YFG']]
... ]
>>> from itertools import chain
>>> items2 = list(chain.from_iterable(items))
>>> items2
[['SKU', 'DHF', 'KSD'], ['KUD', 'HFK', 'SDJ'], ['UDH', 'FKS', 'DJH'], ['KUG', 'UJY', 'FUY'], ['UGU', 'JYF', 'UYF'], ['GUJ', 'YFU', 'YFG']]
>>> items3 = list(chain.from_iterable(items2)) 
>>> items3 
['SKU', 'DHF', 'KSD', 'KUD', 'HFK', 'SDJ', 'UDH', 'FKS', 'DJH', 'KUG', 'UJY', 'FUY', 'UGU', 'JYF', 'UYF', 'GUJ', 'YFU', 'YFG']
Joel Cornett
  • 24,192
  • 9
  • 66
  • 88