Re: Splitting a list

Discussion in 'Python' started by Jeff Epler, Aug 31, 2004.

  1. Jeff Epler

    Jeff Epler Guest

    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)

    iD8DBQFBNIcZJd01MZaTXX0RAj0rAKClAYICBN0jWfcGZFxZGLEnZZfaiACdFlHS
    E9q0hAi2oS9BMpriHM4/m0w=
    =w4T2
    -----END PGP SIGNATURE-----
     
    Jeff Epler, Aug 31, 2004
    #1
    1. Advertising

  2. Jeff Epler

    Peter Otten Guest

    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, Aug 31, 2004
    #2
    1. Advertising

  3. Jeff Epler

    Peter Otten Guest

    Peter Otten, Aug 31, 2004
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. John Ericson
    Replies:
    0
    Views:
    428
    John Ericson
    Jul 19, 2003
  2. Mark
    Replies:
    0
    Views:
    442
  3. John Dibling
    Replies:
    0
    Views:
    417
    John Dibling
    Jul 19, 2003
  4. Rajarshi Guha

    splitting a list into n groups

    Rajarshi Guha, Oct 8, 2003, in forum: Python
    Replies:
    13
    Views:
    491
    Peter Otten
    Oct 9, 2003
  5. Ian Sparks

    Splitting a list

    Ian Sparks, Aug 31, 2004, in forum: Python
    Replies:
    6
    Views:
    359
    Alex Martelli
    Sep 1, 2004
Loading...

Share This Page