list - pythonic方式来分割列表?

标签 list split python

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/

相关文章:

python - 如何在列表中每次运行连续零时删除除 x 之外的所有零?

javascript - 使用 jQuery 使用 split 或 length 将 div 中的 10 位数字拆分为 3,3,4

python - 在python中将2位数字拆分为1 0's and 1' s

python - 'TreeDict'(或 TreeMap )在实践中有什么用?

Python 在 if 语句中等同于 &&(逻辑与)

python - 列表不改组 python

python - 如何检查嵌套在循环内的字典中是否存在值

python - 有没有一种简单的方法可以将 Pandas DataFrame 上的大字符串拆分为相等数量的单词?

python - 根据另一个数据帧中的 boolean 值设置一个数据帧中的值

list - 如何在erlang中将元组列表转换为二进制