-1

I'm currently working on a project for my Introduction to Computer Science lecture and now came across following problem: The Output of my Code are lists which contains lists and I would like to put all object from all those lists into one large list. The ourput looks like this:

[[['0452']], 
 [['1234'], ['176']], 
 [['2245'], ['2345', '2345'], ['2545']], 
 [['3452', '3432'], ['3523']],
 [['44563'], ['4523']],
 [['5234', '5234', '5234'], ['5435'], ['563']],
 [['6435']], 
 [['7134']],
 [['8324']], 
 ['923', '9936']
]
Marat
  • 15,215
  • 2
  • 39
  • 48
  • 3
    Can you post the code you've already written to try and accomplish this? – Michael Bianconi Jan 29 '20 at 17:39
  • 1
    Does this answer your question? [How to make a flat list out of list of lists?](https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-list-of-lists) – Marat Jan 29 '20 at 17:51
  • 2
    What is the issue, exactly? Can you be more specific? – AMC Jan 29 '20 at 17:51

3 Answers3

1

You can use recursion for this as not all sub lists are the same length:

def unpack(iterable):
    res = []
    for x in iterable:
      if isinstance(x, list):
          res.extend(unpack(x))
      else:
          res.append(x)
    return res

>>> data = data = [[['0452']], [['1234'], ['176']], [['2245'], ['2345', '2345'], ['2545']], [['3452', '3432'], ['3523']], [['44563'], ['4523']], [['5234', '5234', '5234'], ['5435'], ['563']], [['6435']], [['7134']], [['8324']], ['923', '9936']]
>>> unpack(data)
['0452', '1234', '176', '2245', '2345', '2345', '2545', '3452', '3432', '3523', '44563', '4523', '5234', '5234', '5234', '5435', '563', '6435', '7134', '8324', '923', '9936']
Jab
  • 26,853
  • 21
  • 75
  • 114
0
big_list=[element for list_ in bigger_list for element in list_]
Mohammed Khalid
  • 155
  • 1
  • 6
  • This does not get just a list of strings. It only partially unpacks the list. – Jab Jan 29 '20 at 17:56
  • Code-only answers are considered low quality: make sure to provide an explanation what your code does and how it solves the problem. It will help the asker and future readers both if you can add more information in your post. See also Explaining entirely code-based answers: https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers – borchvm Jan 30 '20 at 07:20
0

here's the solution:

first convert your output to string then do as follows:

import re
text= "[['0452']], [['1234'], ['176']], [['2245'], ['2345', '2345'], ['2545']], [['3452', '3432'], ['3523']], [['44563'], ['4523']], [['5234', '5234', '5234'], ['5435'], ['563']], [['6435']], [['7134']], [['8324']], ['923', '9936']]" 
pattern = r'[^0-9]'
text = re.sub(pattern, '  ', text)
print(text)

result:

['0452', '1234', '176', '2245', '2345', '2345', '2545', '3452', '3432', '3523', '44563', '4523', '5234', '5234', '5234', '5435', '563', '6435', '7134', '8324', '923', '9936']
Chadee Fouad
  • 2,630
  • 2
  • 23
  • 29