simple way to un-nest (flatten?) list

djc anrnsrisnotreqid at blueyonder.co.uk
Mon Nov 6 18:04:32 EST 2006


George Sakkis wrote:
 > Meet itertools:
 >
 > from itertools import chain
 > names = set(chain(*r.itervalues()))
 > print [line for line in table if line[7] in names]

Steven D'Aprano wrote:
> Assuming you don't care what order the strings are in:
> 
> r = {'a':('ASLIB','Aslib'),'j':('JDOC','jdoc')}
> result = sum(r.values(), ())
> 
> If you do care about the order:
> 
> r = {'a':('ASLIB','Aslib'),'j':('JDOC','jdoc')}
> keys = r.keys()
> keys.sort()
> result = []
> for key in keys:
>     result.extend(r[key])
> result = tuple(result)

Thank you everybody.
As it is possible that the tuples will not always be the same word in 
variant cases
result = sum(r.values(), ())
  will do fine and is as simple as I suspected the answer would be.





-- 
djc



More information about the Python-list mailing list