pythonic方式来分割列表?

发布于 2024-11-15 20:22:12 字数 799 浏览 0 评论 0原文

可能的重复:
如何将列表均匀分割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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

清浅ˋ旧时光 2024-11-22 20:22:12

我只使用列表理解/生成器:

[my_list[x:x+num] for x in range(0, len(my_list), num)]

I'd just use a list comprehension/generator:

[my_list[x:x+num] for x in range(0, len(my_list), num)]
≈。彩虹 2024-11-22 20:22:12
def split_list(lst, num):
    def splitter(lst, num):
        while lst:
            head = lst[:num]
            lst = lst[num:]
            yield head
    return list(splitter(lst, num))

以下是在交互式 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]]
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]]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文