pythonic way to split list? [duplicate]
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?
精彩评论