473,324 Members | 2,268 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,324 software developers and data experts.

split up a list by condition?

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
Jul 19 '05 #1
9 3030
Reinhold,
Thanks for your response in the previous thread.
Yours is an interesting question. I haven't come up with a solution,
but I did realize that in the previous problem, the source 'word'
doesn't really need to stay intact...
So perhaps a solution along these lines?
for a in enumerate(wlist):

.... if a[1] in vowels:
.... vees.append(wlist.pop(a[0]))

I don't know if it's possible to cram a 'pop' command into the single
line solution though.

I look forward to seeing other tricks to this end... :)

Jul 19 '05 #2
Sounds like itertools.groupby() is what you're looking for, just sort
your sequence on the grouping func that you will pass as 2nd arg to
groupby(), before you pass the sequence to groupby()

http://www.python.org/doc/2.4/whatsnew/node13.html
http://www.python.org/dev/doc/devel/...functions.html

Jul 19 '05 #3
>> 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


Trying to compress too much into one line is not "the python way" ;-)
vees, cons = [], []
for c in reversed(wlist):
if c in vocals:
vees.append(c)
else:
cons.append(c)

Jul 19 '05 #4
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.
Jul 19 '05 #5
Raymond Hettinger wrote:
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

Trying to compress too much into one line is not "the python way" ;-)


I know (there is a Guido quote about this, I just lost the source...)
vees, cons = [], []
for c in reversed(wlist):
if c in vocals:
vees.append(c)
else:
cons.append(c)


Well, I've found a uglier solution,

vees, cons = [], []
[(vees, cons)[ch in vocals].append(ch) for ch in wlist]

Reinhold
Jul 19 '05 #6
Duncan Booth wrote:
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:


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


This is clear. I actually wanted to know if there is a function which I
overlooked which does that, which wouldn't be a maintenance nightmare at all.

Reinhold
Jul 19 '05 #7
> vees, cons = [], []
[(vees, cons)[ch in vocals].append(ch) for ch in wlist]


Wow, that's horribly twisted Reinhold...
I spent about an hour last night trying something similar, to no end...
:)

Neat tricks people...
I like Duncan's use of "or" to solve it.
I didn't see that in the python docs on list comprehension.
Very cool.

There is a special place in my heart for obfuscated Python,
but of course, not in production code if there is a clearer solution
available.

Jul 19 '05 #8
Re-run this with the input string "The quick brown fox is named
'Aloysius'." and we discover that 'A', 'y', "'" and '.' are also
consonants. (Actually, this is bug-compatible with the OP's original
example.)

-- Paul

Jul 19 '05 #9
Reinhold Birkenfeld wrote:
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)
This is clear. I actually wanted to know if there is a function which I
overlooked which does that, which wouldn't be a maintenance nightmare at
all.


Not that I know of, but if there is one it should be named
"bifilter", or "difilter" if you prefer Greek roots. :)
def bifilter(test, seq):
passes = []
fails = []
for term in seq:
if test(term):
passes.append(term)
else:
fails.append(term)
return passes, fails

bifilter("aeiou".__contains__, "This is a test") (['i', 'i', 'a', 'e'], ['T', 'h', 's', ' ', 's', ' ', ' ', 't', 's', 't'])
Another implementation, though in this case I cheat because I
do the test twice, is
from itertools import ifilter, ifilterfalse, tee
def bifilter(test, seq): .... seq1, seq2 = tee(seq)
.... return ifilter(test, seq1), ifilterfalse(test, seq2)
.... bifilter("aeiou".__contains__, "This is another test") (<itertools.ifilter object at 0x57f050>, <itertools.ifilterfalse object at 0x57f070>) map(list, _) [['i', 'i', 'a', 'o', 'e', 'e'], ['T', 'h', 's', ' ', 's', ' ', 'n', 't', 'h', 'r', ' ', 't', 's', 't']]

Andrew
da***@dalkescientific.com

Jul 19 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Stu Cazzo | last post by:
I have the following: String myStringArray; String myString = "98 99 100"; I want to split up myString and put it into myStringArray. If I use this: myStringArray = myString.split(" "); it...
9
by: Will McGugan | last post by:
Hi, I'm curious about the behaviour of the str.split() when applied to empty strings. "".split() returns an empty list, however.. "".split("*") returns a list containing one empty string. ...
20
by: William Stacey [MVP] | last post by:
int list = {1,2,3,4,5,6}; Function to randomize the list? Cheers! -- William Stacey, MVP
3
by: John Salerno | last post by:
This is an example in the book I'm reading: string fullName = " Edward C Koop "; fullName = fullName.Trim(); string names = fullName.Split(' '); string firstName = names; //...
3
by: David Pratt | last post by:
Hi. I am splitting a string on a non whitespace character. One or more whitespace characters can be returned as items in the list. I do not want the items in the list that are only whitespace (can...
9
by: dtex23 | last post by:
Good afternoon all, Question about list assignment in perl... Given a piece of code that looks kinda like this for parsing some '|' delimited input text lines : ($var1, $var2, $var3) =...
0
VbaNewbee
by: VbaNewbee | last post by:
I have a form with a few filters. Once the user clicks "search button", the code first evaluates my filters, then shows the query results in a List Box" titled backschedule. I have a few text...
12
by: Philip Mueller | last post by:
Hi, I am using multiple stl::list s of different types. Now I want to write a function list<type>::iterator s_erase(list<typel, list<type>::iterator it) that takes an iterator and deletes...
0
by: Tim Chase | last post by:
Is there a functional way to do this? Sounds like a use for a generator wrapper: def monotonic(iterator): i = iter(iterator) prev = i.next() yield prev while True:
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.