2011-06-16 39 views
2

可能重複:
How do you split a list into evenly sized chunks in Python?pythonic方式來分割列表?

我有一個函數象下面這樣:

def split_list(self,my_list,num):  
    .....  
    ..... 

其中my_list是:

my_list = [['1','one'],['2','two'],['3','three'],['4','four'],['5','five'],['6','six'],['7','seven'],['8','eight']] 

我想由下式給出NUM分裂列表:

即如果num = 3 然後輸出將是:[[['1','one'],['2','two'],['3','three']],[['4','four'],['5','five'],['6','six']],[['7','seven'],['8','eight']]]

如果num = 4然後

[[['1','one'],['2','two'],['3','three'],['4','four']],[['5','five'],['6','six'],['7','seven'],['8','eight']]] 
+1

@DrTyrsa:這是不同的。在那裏指定了塊大小,這裏是塊的數量。 – 2011-06-16 09:36:10

+0

@Felix Kling:不,這是完全重複的。 – Kimvais 2011-06-16 09:37:55

+1

@Felix Kling我看到'num = 4'的兩個塊。你呢? – DrTyrsa 2011-06-16 09:37:57

回答

3

我只是使用列表理解/發電機:

[my_list[x:x+num] for x in range(0, len(my_list), num)] 
0
def split_list(lst, num): 
    def splitter(lst, num): 
     while lst: 
      head = lst[:num] 
      lst = lst[num:] 
      yield head 
    return list(splitter(lst, num)) 

下面是從一個摘錄在交互式外殼中運行:

>>> def split_list(lst, num): 
...  def splitter(lst, num): 
...   while lst: 
...    head = lst[:num] 
...    lst = lst[num:] 
...    yield head 
...  return list(splitter(lst, num)) 
... 
>>> split_list(range(10), 3) 
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]