开发者

pythonic way to split list? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How do you split a list into evenly sized chunks in Python?

I Have a function like below:

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

where my_list is:

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

I want to split list by given num:

i.e if num = 3 then output will be : [[['1','one'],['2','two'],['3','three']],[['4','four'],['5','five'],['6','six']],[['7','seven'],['8','eight']]]

if num =4 then

[[['1','one'],['2','two'],['3','three'],['4','fo开发者_开发百科ur']],[['5','five'],['6','six'],['7','seven'],['8','eight']]]


I'd just use a list comprehension/generator:

[my_list[x:x+num] for x in range(0, len(my_list), 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))

Here is an excerpt from running this in the interactive 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]]


Try to read this: How do you split a list into evenly sized chunks?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜