split up a list by condition?

Duncan Booth duncan.booth at invalid.invalid
Tue Jun 7 10:50:10 CEST 2005


Reinhold Birkenfeld wrote:

> Hi,
> 
> while writing my solution for "The python way?", I came across this
> fragment: 
> 
>     vees = [c for c in wlist[::-1] if c in vocals]
>     cons = [c for c in wlist[::-1] if c not in vocals]
> 
> So I think: Have I overlooked a function which splits up a sequence
> into two, based on a condition? Such as
> 
> vees, cons = split(wlist[::-1], lambda c: c in vocals)
> 
> Reinhold

If you really are being charged by the number of newline characters in your 
code you could write:

>>> wlist = list('The quick brown fox')
>>> vowels = 'aeiuo'
>>> cons = []
>>> vees = [ c for c in wlist if c in vowels or cons.append(c) ]
>>> cons
['T', 'h', ' ', 'q', 'c', 'k', ' ', 'b', 'r', 'w', 'n', ' ', 'f', 'x']
>>> vees
['e', 'u', 'i', 'o', 'o']
>>> cons = []
>>> vees = [ c for c in wlist[::-1] if c in vowels or cons.append(c) ]
>>> cons
['x', 'f', ' ', 'n', 'w', 'r', 'b', ' ', 'k', 'c', 'q', ' ', 'h', 'T']
>>> vees
['o', 'o', 'i', 'u', 'e']

but every penny you save writing a one liner will be tuppence extra on 
maintenance.



More information about the Python-list mailing list