2013-10-24 39 views
1

我想將符合謂詞的連續元素分組。一種這樣的函數文檔測試看起來像Python - 分組滿足謂詞的連續元素

>>> group([1, 2, 3, 0, 4, 5, 0, 0, 6], lambda x: x != 0) 
    [[1, 2, 3], [4, 5], [6]] 
>>> group([1, 2, 3, 0, 4, 5, 0, 0, 6], lambda x: x == 0) 
    [[0], [0, 0]] 

我寫了一個原型,我使用itertool的takewhile,而是因爲我一直名單和國際熱核實驗堆之間鑄造它的醜陋。我也不想堅持閱讀列表的索引,因爲它感覺效率低下。有人能指點我如何以正確的方式將itertools混合在一起嗎?

from itertools import takewhile 

def group(l, p): 
    blocks = [] 
    while True: 
     i = iter(l) 
     taken = list(takewhile(p, i)) 
     l = list(i) 
     if len(taken) > 0: 
      blocks.append(taken) 
     if len(l) == 0: 
      return blocks 

謝謝!

+4

出了什麼問題'itertools.groupby'? –

+0

無法解決如何使用它,但現在我可以。謝謝大家。 – Derek

回答

4

你可以使用itertools.groupby

In [22]: import itertools as IT 

In [23]: [list(g) for k, g in IT.groupby(
      [1, 2, 3, 0, 4, 5, 0, 0, 6], lambda x: x != 0) if k] 
Out[23]: [[1, 2, 3], [4, 5], [6]] 
1

使用itertools.groupby

>>> import itertools 
>>> 
>>> data = [1, 2, 3, 0, 4, 5, 0, 0, 6] 
>>> xs = [list(grp) for k, grp in itertools.groupby([1, 2, 3, 0, 4, 5, 0, 0, 6], lambda x: x == 0)] 
>>> xs 
[[1, 2, 3], [0], [4, 5], [0, 0], [6]] 

>>> xs[data[0] == 0::2] 
[[1, 2, 3], [4, 5], [6]] 
>>> xs[data[0] != 0::2] 
[[0], [0, 0]] 
相關問題