pythonic方式来分割列表?
可能的重复:
如何将列表均匀分割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 拆分列表:
即如果 num = 3 那么输出将是:[[['1','one'],['2','two'],['3','third']],[['4','four' ],['5','五'],['6','六']],[['7','七'],['8','八']]]
if则num=4
[[['1','one'],['2','two'],['3','three'],['4','four']],[['5','five'],['6','six'],['7','seven'],['8','eight']]]
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','four']],[['5','five'],['6','six'],['7','seven'],['8','eight']]]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我只使用列表理解/生成器:
I'd just use a list comprehension/generator:
以下是在交互式 shell 中运行此命令的摘录:
Here is an excerpt from running this in the interactive shell:
尝试阅读以下内容: 你怎么样将列表分割成大小均匀的块?
Try to read this: How do you split a list into evenly sized chunks?