1

I have a list that contains other lists:

list_of_lists = [[['2019-03-27-16:08:21 Now:(87.0866) Epoch:(1553728101) 45(secs)ago ItemID:(51141)', '2019-03-20-16:09:21 7d:(87.2040) Epoch:(1553123361) 604785(secs)ago ItemID:(51141)', 'Interval:(1m) Diff:(-0.1174) Now_[less-than]_Past(7d) GPM:(0.00008153) +GROWTH'], 'OK: Date:[2021-04-07 10:43:10.037075] Days.Until:[741.773648417]']]

How do I merge these lists into one list so that it looks like this:

['2019-03-27-16:08:21 Now:(87.0866) Epoch:(1553728101) 45(secs)ago ItemID:(51141)', '2019-03-20-16:09:21 7d:(87.2040) Epoch:(1553123361) 604785(secs)ago ItemID:(51141)', 'Interval:(1m) Diff:(-0.1174) Now_[less-than]_Past(7d) GPM:(0.00008153) +GROWTH', 'OK: Date:[2021-04-07 10:43:10.037075] Days.Until:[741.773648417]']

I've found some code online but it doesn't do what I want:

flattened_list = [y for x in list_of_lists for y in x]

I also would prefer a solution that does not involve having to pip install any modules that isn't part of the default python package.

Dev Ops
  • 127
  • 1
  • 10

2 Answers2

1

With a simple recursive method you can handle any level of nesting:

def flat(l):
    if isinstance(l, list):
        result = []
        for i in l:
            result = result + flat(i)
        return result
    else:
        return [l]

>>> flat(list_of_lists)
['2019-03-27-16:08:21 Now:(87.0866) Epoch:(1553728101) 45(secs)ago ItemID:(51141)', '2019-03-20-16:09:21 7d:(87.2040) Epoch:(1553123361) 604785(secs)ago ItemID:(51141)', 'Interval:(1m) Diff:(-0.1174) Now_[less-than]_Past(7d) GPM:(0.00008153) +GROWTH', 'OK: Date:[2021-04-07 10:43:10.037075] Days.Until:[741.773648417]']

Another example:

>>> flat([1,2,[3,[4,5]],6,[7,8]])
[1, 2, 3, 4, 5, 6, 7, 8]
dcg
  • 4,187
  • 1
  • 18
  • 32
0

Because some of the items in your list contains lists and others don't, the simple flatten options cannot be used directly. I would suggest creating a function that will flatten the list of lists recursively (including items that are lists themselves):

def flatten(aList):
    if not isinstance(aList,list): return [aList]
    return [ item for subList in aList for item in flatten(subList)] 

flattened_list = flatten(list_of_lists)
Alain T.
  • 40,517
  • 4
  • 31
  • 51