Pythonic方式将逗号分隔数字分成对

jsa*_*msa 17 python tuples

我想将逗号分隔值拆分成对:

>>> 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)]
Run Code Online (Sandbox Code Playgroud)

会是什么Python的#什么样子呢?

你如何检测和处理一组奇数的字符串?

Fog*_*ird 44

就像是:

zip(t[::2], t[1::2])
Run Code Online (Sandbox Code Playgroud)

完整示例:

>>> 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)]
>>>
Run Code Online (Sandbox Code Playgroud)

如果项目数为奇数,则将忽略最后一个元素.仅包括完整的配对.


Pao*_*ino 8

这个怎么样:

>>> 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')]
Run Code Online (Sandbox Code Playgroud)

这也很好地处理不均匀的金额:

>>> 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',)]
Run Code Online (Sandbox Code Playgroud)

PS我把这个代码藏起来了,我才意识到我从哪里得到它.stackoverflow中有两个非常相似的问题:

还有来自食谱部分的这个宝石itertools:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)
Run Code Online (Sandbox Code Playgroud)


Ant*_*sma 8

一个更通用的选项,它也适用于迭代器并允许组合任意数量的项:

 def n_wise(seq, n):
     return zip(*([iter(seq)]*n))
Run Code Online (Sandbox Code Playgroud)

如果要获取惰性迭代器而不是列表,请使用itertools.izip替换zip.