Skip to content Skip to sidebar Skip to footer

Pythonic Way To Split Comma Separated Numbers Into Pairs

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), (

Solution 1:

Something like:

zip(t[::2], t[1::2])

Full example:

>>>s = ','.join(str(i) for i inrange(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.

Solution 2:

A more general option, that also works on iterators and allows for combining any number of items:

defn_wise(seq, n):
     returnzip(*([iter(seq)]*n))

Replace zip with itertools.izip if you want to get a lazy iterator instead of a list.

Solution 3:

How about this:

>>> x = '0,1,2,3,4,5,6,7,8,9'.split(',')
>>> defchunker(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:

defgrouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

Solution 4:

A solution much like FogleBirds, but using an iterator (a generator expression) instead of list comprehension.

s = '0,1,2,3,4,5,6,7,8,9'# generator expression creating an iterator yielding numbersiterator = (int(i) for i in s.split(','))

# use zip to create pairs# (will ignore last item if odd number of items)# Note that zip() returns a list in Python 2.x, # in Python 3 it returns an iteratorpairs = zip(iterator, iterator)

Both list comprehensions and generator expressions would probably be considered quite "pythonic".

Solution 5:

This will ignore the last number in an odd list:

n = [int(x) forx in s.split(',')]
print zip(n[::2], n[1::2])

This will pad the shorter list by 0 in an odd list:

importitertoolsn= [int(x) for x in s.split(',')]
print list(itertools.izip_longest(n[::2], n[1::2], fillvalue=0))

izip_longest is available in Python 2.6.

Post a Comment for "Pythonic Way To Split Comma Separated Numbers Into Pairs"