pythonic方式拆分列表?

时间:2011-06-16 09:31:53

标签: list split python

  

可能重复:
  How do you split a list into evenly sized chunks in Python?

我有如下功能:

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

3 个答案:

答案 0 :(得分:3)

我只使用列表理解/生成器:

[my_list[x:x+num] for x in range(0, len(my_list), num)]

答案 1 :(得分: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))

以下是在交互式shell中运行此代码的摘录:

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

答案 2 :(得分:0)