Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: Splitting a list

Reply
Thread Tools

Re: Splitting a list

 
 
Jeff Epler
Guest
Posts: n/a
 
      08-31-2004
Here's my version as a generator function:
def split(it, elem):
l = []
for i in it:
if i == elem:
yield l
l = []
else:
l.append(i)
yield l

>>> list(split(" a b c ", " "))

[[], ['a'], ['b'], ['c'], []]
>>> " a b c ".split(" ")

['', 'a', 'b', 'c', '']
>>> l = [1,2,3,-1,4,5,-1,8,9]
>>> list(split(l, -1))

[[1, 2, 3], [4, 5], [8, 9]]

Jeff

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.5 (GNU/Linux)

iD8DBQFBNIcZJd01MZaTXX0RAj0rAKClAYICBN0jWfcGZFxZGL EnZZfaiACdFlHS
E9q0hAi2oS9BMpriHM4/m0w=
=w4T2
-----END PGP SIGNATURE-----

 
Reply With Quote
 
 
 
 
Peter Otten
Guest
Posts: n/a
 
      08-31-2004
Jeff Epler wrote:

> Here's my version as a generator function:
> def split(it, elem):
> l = []
> for i in it:
> if i == elem:
> yield l
> l = []
> else:
> l.append(i)
> yield l
>


A clean algorithm, but it has one corner case that strikes me as
counterintuitive:

>>> list(split([], None))

[[]]

I would prefer [], so I cross-checked with str.split():

>>> "".split()

[]
>>> "".split("x")

['']

Strange. Is that by design or by accident?

Peter


 
Reply With Quote
 
 
 
 
Peter Otten
Guest
Posts: n/a
 
      08-31-2004
Peter Otten wrote:

.... before memory kicked in.

http://groups.google.com/groups?selm...s.t-online.com

Sorry.

Peter

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Splitting a list Ian Sparks Python 6 09-01-2004 07:32 AM
splitting a list into n groups Rajarshi Guha Python 13 10-09-2003 01:11 PM
Re: Splitting up the definitions of a class into different files (splitting public from private)? John Dibling C++ 0 07-19-2003 04:41 PM
Re: Splitting up the definitions of a class into different files (splitting public from private)? Mark C++ 0 07-19-2003 04:24 PM
Re: Splitting up the definitions of a class into different files (splitting public from private)? John Ericson C++ 0 07-19-2003 04:03 PM



Advertisments