tricky nested list unpacking problem

Steve Holden steve at holdenweb.com
Tue Dec 16 12:18:07 EST 2008


Chris Rebert wrote:
> 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'
> 
Read the problem description again ...

regards
 Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list