[Tutor] flattening a list

Chad Crabtree flaxeater at yahoo.com
Thu Jan 13 19:53:28 CET 2005


You should post this on the Python Cookbook
http://aspn.activestate.com/ASPN/Python/Cookbook/

Orri Ganel wrote

> Bill Kranec wrote:
>
>
>
>> Hello,
>
>
>>
>
>> I have a list of lists, for example [ [1,2] , [3,4] ], and I would

>
>
>> like to pass all the elements of that list as arguments to a
function 
>
>
>> (for example the intersection of all list elements).  Is there a 
>
>
>> command in regular Python to do this?  I would like to avoid the 
>
>
>> hassle and speed hit of a loop to extract all the list elements.
>
>
>>
>
>> In the past, I believe I have used something like flatten(list),
which 
>
>
>> was part of Numarray (I think).  Am I missing an obvious or clever

>
>
>> solution in regular Python?
>
>
>>
>
>> Thanks for your help!
>
>
>>
>
>> Bill
>
>
>> _______________________________________________
>
>
>> Tutor maillist  -  Tutor at python.org
>
>
>> http://mail.python.org/mailman/listinfo/tutor
>
>
>>
>
> Well, here's something i put together (works for lists and tuples,
> ignores strings and dicts):
>
>
>
> ### Start Code ###
>
> def flatten(sequence):
>
>
>
>    def rflat(seq2):
>
>        seq = []
>
>        for entry in seq2:
>
>            if '__contains__' in dir(entry) and \
>
>                         type(entry) != str and \
>
>                         type(entry)!=dict:
>
>                seq.extend([i for i in entry])
>
>            else:
>
>                seq.append(entry)
>
>        return seq
>
>
>
>    def seqin(sequence):
>
>        for i in sequence:
>
>            if '__contains__' in dir(i) and \
>
>                         type(i) != str and \
>
>                         type(i) != dict:
>
>                return True
>
>        return False
>
>
>
>    seq = sequence[:]
>
>    while seqin(seq):
>
>        seq = rflat(seq)
>
>    return seq
>
> ### End Code ###
>
>
>
> Tested it on a few different scenarios, all performed as expected:
>
>
>
> >>> flatten([1])
>
> [1]
>
> >>> flatten([1,[1]])
>
> [1, 1]
>
> >>> flatten(['ab',1])
>
> ['ab', 1]
>
> >>> flatten([10,(34,42),54,'abc'])
>
> [10, 34, 42, 54, 'abc']
>
> >>> flatten([{'abc':[1,2,3]},[{'a':'1'},{'[1,2]':'ab'}]])
>
> [{'abc': [1, 2, 3]}, {'a': '1'}, {'[1,2]': 'ab'}]
>
>
>
> Cheers,
>
> Orri
>




		
__________________________________ 
Do you Yahoo!? 
The all-new My Yahoo! - Get yours free! 
http://my.yahoo.com 
 



More information about the Tutor mailing list