1

In Python3

If I have some complex lists such like:

[1, [2, 3], [4, 5, 6]]

or maybe looks like:

[1, [2, [3]], 4, [5, 6]]

I‘m sure there is no repeat value in this list, but I don't know what the list's exactly structure is.

how can I extract the values (recursive) from this complex uncertain list? I want to get a plain list consist of these values:

[1, 2, 3, 4, 5, 6]

Is there any elegant way to solve this issue?

Laisky
  • 55
  • 5

1 Answers1

0

Example:

>>> from compiler.ast import flatten
>>> flatten([0, [1, 2], [3, 4, [5, 6]], 7])
[0, 1, 2, 3, 4, 5, 6, 7]

Try this:

import re

def Flatten(TheList):
    a = str(TheList)
    b,crap = re.subn(r'[\[,\]]', ' ', a)
    c = b.split()
    d = [int(x) for x in c]

    return(d)
lakshmen
  • 28,346
  • 66
  • 178
  • 276
  • Input: [1, 2, [3]] Raise: TypeError: 'int' object is not iterable – Laisky Aug 21 '14 at 08:28
  • and also doesn't work to [["a", "b", ["d"]], ["c"]] – Laisky Aug 21 '14 at 08:29
  • changed the solution sorry.. – lakshmen Aug 21 '14 at 08:41
  • em, the module compiler has been removed in python3, I have seen [Flatten (an irregular) list of lists in Python](http://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python). it seems like there isn't any elegant(simply) solution – Laisky Aug 21 '14 at 08:59