simple way to un-nest (flatten?) list
Steven D'Aprano
steve at REMOVE.THIS.cybersource.com.au
Mon Nov 6 05:43:13 EST 2006
On Sun, 05 Nov 2006 21:43:33 +0000, djc wrote:
> There is I am sure an easy way to do this, but I seem to be brain dead
> tonight. So:
>
> I have a table such that I can do
>
> [line for line in table if line[7]=='JDOC']
> and
> [line for line in table if line[7]=='Aslib']
> and
> [line for line in table if line[7]=='ASLIB']
> etc
>
> I also have a dictionary
> r= {'a':('ASLIB','Aslib'),'j':('JDOC', 'jdoc')}
> so I can extract values
> r.values()
> [('ASLIB', 'Aslib'), ('JDOC', 'jdoc')]
>
> I would like to do
>
> [line for line in table if line[7] in ('JDOC','jdoc','Aslib','ASLIB')]
What is the purpose of the "if line[7]" bit?
> so how should I get from
> {'a':('ASLIB','Aslib'),'j':('JDOC','jdoc')}
> to
> ('Aslib','ASLIB','JDOC','jdoc')
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)
--
Steven.
More information about the Python-list
mailing list