Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to split comma separated numbers into pairs

Tags:

python

tuples

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?

like image 288
jsamsa Avatar asked May 15 '09 20:05

jsamsa


3 Answers

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.

like image 172
FogleBird Avatar answered Nov 21 '22 00:11

FogleBird


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.

like image 40
Ants Aasma Avatar answered Nov 20 '22 22:11

Ants Aasma


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:

  • What is the most “pythonic” way to iterate over a list in chunks?
  • How do you split a list into evenly sized chunks in Python?

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)
like image 8
Paolo Bergantino Avatar answered Nov 20 '22 23:11

Paolo Bergantino