list comprehension for splitting strings into pairs
Steven Bethard
steven.bethard at gmail.com
Tue Oct 12 19:44:51 EDT 2004
Russell Blau <russblau <at> hotmail.com> writes:
> >>> lst = ['1', '1:2', '3', '-1:4']
> >>> splits = [':' in item and item.split(':', 1) or [item, None]
> for item in lst]
> >>> splits
> [['1', None], ['1', '2'], ['3', None], ['-1', '4']]
Oooh. Pretty. =)
What if I want to convert my splits list to:
[[1, None], [1, 2], [3, None], [-1, 4]]
where I actually call int on each of the non-None items? Obviously I could
extend your example to:
>>> lst = ['1', '1:2', '3', '-1:4']
>>> splits = [':' in item and [int(x) for x in item.split(':', 1)]
... or [int(item), None]
... for item in lst]
>>> splits
[[1, None], [1, 2], [3, None], [-1, 4]]
But that's getting to be a bit more work than looks good to me in a list
comprehension. I thought about doing it in two steps:
>>> splits = [':' in item and item.split(':', 1) or [item, None]
... for item in lst]
>>> splits = [[int(i), p is not None and int(p) or p]
... for i, p in splits]
>>> splits
[[1, None], [1, 2], [3, None], [-1, 4]]
This looks decent to me, but if you see a better way, I'd love to hear about
it. =)
Thanks again!
Steve
More information about the Python-list
mailing list