2009-05-15 119 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