Possible Duplicate:
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']]]
最佳答案
我只使用列表理解/生成器:
[my_list[x:x+num] for x in range(0, len(my_list), num)]
关于list - pythonic方式来分割列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6369734/