tricky nested list unpacking problem

Chris Rebert clp at rebertia.com
Mon Dec 15 21:03:14 CET 2008


On Mon, Dec 15, 2008 at 11:06 AM, Reckoner <reckoner at gmail.com> wrote:
> Hi,
>
> I have lists of the following type:
>
> [1,2,3,[5,6]]
>
> and I want to produce the following strings from this as
>
> '0-1-2-3-5'
> '0-1-2-3-6'
>
> That was easy enough. The problem is that these can be nested. For
> example:
>
> [1,2,3,[5,6],[7,8,9]]
>
> which should produce
>
> '0-1-2-3-5-7'
> '0-1-2-3-5-8'
> '0-1-2-3-5-9'
> '0-1-2-3-6-7'
> '0-1-2-3-6-8'
> '0-1-2-3-6-9'
>
> also,
>
> [1,2,3,[5,6],7,[9]]
>
> should produce
>
> '0-1-2-3-5-7-9'
> '0-1-2-3-6-7-9'
>
> obviously, these are nested loops over the lists. The problem is that
> I don't know ahead of time how many lists there are or how deep they
> go. In other words, you could have:
>
> [1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]]
>
> Any help appreciated. I've really been having trouble with this.
>
> I hope that made sense.

You just need a recursive list-flattening function. There are many
recipes for these. Here's mine:

def flatten(lst):
    if isinstance(lst, list):
        result = []
        for item in lst:
            result += flatten(item)
        return result
    else:
        return [lst]

>>> flattened = flatten([1,2,3,[5,6,[10, 11]],7,[9,[1, 2, 3, 4, 5 ]]])
>>> flattened
[1, 2, 3, 5, 6, 10, 11, 7, 9, 1, 2, 3, 4, 5]
>>> '-'.join(str(num) for num in flattened)
'1-2-3-5-6-10-11-7-9-1-2-3-4-5'

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list