list comprehension for splitting strings into pairs

Martin Maney maney at pobox.com
Thu Oct 14 15:10:36 EDT 2004


Steven Bethard <steven.bethard at gmail.com> wrote:
>>>> lst = ['1', '1:2', '3', '-1:4']
>>>> splits = []
>>>> for s in lst:
> ....    pair = s.split(':')
> ....    if len(pair) != 2:
> ....            pair.append(None)
> ....    splits.append(pair)
> ....    
>>>> splits
> [['1', None], ['1', '2'], ['3', None], ['-1', '4']]

> Basically, I want to split each string into two items, substituting
> None when no second item is specified in the string.  (As you can see,
> in my strings, the items are delimited by ':').

Ah!

>>> lst = ['1', '1:2', '3', '-1:4']
>>> [ (x.split(':') + [None])[:2] for x in lst] 
[['1', None], ['1', '2'], ['3', None], ['-1', '4']]

Handles both single-element and more-than-two-element strings.  Doesn't
crash on empty strings, but the result probably isn't useful:

>>> [ (x.split(':') + [None])[:2] for x in ['1', '1:2', '3', '-1:4', '']] 
[['1', None], ['1', '2'], ['3', None], ['-1', '4'], ['', None]]

You might also enjoy this variation

>>> [ (map(int, x.split(':')) + [None])[:2] for x in lst] 
[[1, None], [1, 2], [3, None], [-1, 4]]

Since I saw you mention wanting that later, I think.  Didn't see any
replies quite the same as this (but I didn't troll through the rest of
the spool looking for possible unthreaded replies).

-- 
One discharges fancy homunculi from one's scheme
by organizing armies of idiots to do the work.  -- Dennett



More information about the Python-list mailing list