I'd like to split a comma separated value into pairs:
>>> s = '0,1,2,3,4,5,6,7,8,9'
>>> pairs = # something pythonic
>>> pairs
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
What would # something pythonic look like?
How would you detect and handle a string with an odd set of numbers?
Something like:
zip(t[::2], t[1::2])
Full example:
>>> s = ','.join(str(i) for i in range(10))
>>> s
'0,1,2,3,4,5,6,7,8,9'
>>> t = [int(i) for i in s.split(',')]
>>> t
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> p = zip(t[::2], t[1::2])
>>> p
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
>>>
If the number of items is odd, the last element will be ignored. Only complete pairs will be included.
A more general option, that also works on iterators and allows for combining any number of items:
def n_wise(seq, n):
return zip(*([iter(seq)]*n))
Replace zip with itertools.izip if you want to get a lazy iterator instead of a list.
How about this:
>>> x = '0,1,2,3,4,5,6,7,8,9'.split(',')
>>> def chunker(seq, size):
... return (tuple(seq[pos:pos + size]) for pos in xrange(0, len(seq), size))
...
>>> list(chunker(x, 2))
[('0', '1'), ('2', '3'), ('4', '5'), ('6', '7'), ('8', '9')]
This will also nicely handle uneven amounts:
>>> x = '0,1,2,3,4,5,6,7,8,9,10'.split(',')
>>> list(chunker(x, 2))
[('0', '1'), ('2', '3'), ('4', '5'), ('6', '7'), ('8', '9'), ('10',)]
P.S. I had this code stashed away and I just realized where I got it from. There's two very similar questions in stackoverflow about this:
There's also this gem from the Recipes section of itertools
:
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With