Velocity Reviews > Re: Splitting a list

# 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-----

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

Peter Otten
Guest
Posts: n/a

 08-31-2004
Peter Otten wrote:

.... before memory kicked in.

Sorry.

Peter