2009-05-15 122 views
17

我想一个逗号分隔值分成对:分裂逗号Python的方式分隔的数字成对

>>> 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)] 

会是什么#Python的东西样子?

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

+0

的可能重复[你怎么分割成列表在Python均匀大小的块?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly- python) – tzot 2011-02-27 22:12:59

回答

44

喜欢的东西:

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

完整的示例:

>>> 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)] 
>>> 

如果项目的数量为奇数,则最后一个元素将被忽略。只有完整的配对才会包含在内。

+13

上帝我爱Python ... – 0x6adb015 2009-05-15 20:21:50

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')] 

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

>>> 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',)] 

附:我把这段代码隐藏起来,我才意识到我从哪里得到它。有一个在计算器两个非常相似的问题,这个问题:

还有从itertoolsRecipes节这个宝石:

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

如果len(r)%2:r.append(0) – jsamsa 2009-05-15 20:31:36

2

这将忽略最后在一个奇怪的表号:

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

这将垫在奇数列表较短列表由0:

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

izip_longest可用在Python 2.6。

+0

或与“残废”Python 2.5: 这需要神秘到下一个级别 – 2009-05-31 05:18:37

8

一个更普遍的选择,这也适用于迭代器,并允许组合任意数量的项目:

def n_wise(seq, n): 
    return zip(*([iter(seq)]*n)) 

与itertools.izip更换拉链,如果你想获得一个懒惰的迭代器,而不是一个列表。

+1

我不认为搜索块 – YGA 2009-05-29 22:08:59

+0

特别是。复制迭代器部分。 ;-) 很酷,不过。 – Plumenator 2010-07-28 06:13:12

4

溶液很像FogleBirds,但使用代替列表理解迭代器(发电机表达)。

s = '0,1,2,3,4,5,6,7,8,9' 
# generator expression creating an iterator yielding numbers 
iterator = (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 iterator 
pairs = zip(iterator, iterator) 

列表解析和生成器表达式都可能被认为是相当“pythonic”。

+1

这个有助于理解蚂蚁Aasma的代码。 – Plumenator 2010-07-28 06:15:13