【问题标题】:Split a list into smaller lists where each smaller list is subsequently smaller by using list comprehension使用列表推导将列表拆分为较小的列表,其中每个较小的列表随后会更小
【发布时间】:2018-10-10 15:25:30
【问题描述】:

我有一个列表,我想将其拆分为列表列表,这样新列表中的每个列表都会小一个元素。

例如:

exampleList = [1,2,3,4,5,6,7,8,9,10]

newList = [[1,2,3,4,5,6,7,8,9,10],
       [2,3,4,5,6,7,8,9,10],
       [3,4,5,6,7,8,9,10],
       [4,5,6,7,8,9,10],
       [5,6,7,8,9,10],
       [6,7,8,9,10],
       [7,8,9,10],
       [8,9,10],
       [9,10]]

有没有简单的方法通过列表理解来做到这一点?

【问题讨论】:

    标签: python python-2.7 split list-comprehension


    【解决方案1】:

    您可以使用切片和列表推导。

    >>> [exampleList[i:] for i in range(len(exampleList) - 1)] 
    [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [2, 3, 4, 5, 6, 7, 8, 9, 10], [3, 4, 5, 6, 7, 8, 9, 10], [4, 5, 6, 7, 8, 9, 10], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10]]
    

    exampleList[i:] 会将当前索引i 中的所有元素带到末尾。如果您想在结果中包含[10],请在对len 的调用中省略- 1

    【讨论】:

      【解决方案2】:

      使用@timgeb 解决方案,替代版本可能是

      res = [lst[i:] for i, _ in enumerate(lst[:-1])]
      

      使用map的其他可能性

      res = list(map(lambda x: lst[x-1:], lst[:-1]))
      # [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [2, 3, 4, 5, 6, 7, 8, 9, 10], [3, 4, 5, 6, 7, 8, 9, 10], [4, 5, 6, 7, 8, 9, 10], [5, 6, 7, 8, 9, 10], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10], [9, 10]]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-12
        • 1970-01-01
        • 2012-11-04
        • 1970-01-01
        • 2010-12-11
        • 2020-05-05
        • 1970-01-01
        • 2010-10-19
        相关资源
        最近更新 更多