【问题标题】:pythonic way to split list? [duplicate]pythonic拆分列表的方法? [复制]
【发布时间】:2011-06-16 09:31:53
【问题描述】:

可能重复:
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']]]

【问题讨论】:

  • @DrTyrsa:那是不同的。那里指定了块大小,这里指定了块的数量。
  • @Felix Kling:不,这是完全重复的。
  • @Felix Kling 我看到num=4 的两个块。你呢?
  • @DrTyrsa:我很抱歉。我不知何故被这两个元素列表弄糊涂了……

标签: list split python


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:
    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]]
    

    【讨论】:

      【解决方案3】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-03-31
        • 2012-11-18
        • 1970-01-01
        • 1970-01-01
        • 2013-09-10
        • 2017-06-26
        • 2019-12-04
        相关资源
        最近更新 更多