【问题标题】:Slicing a list into n nearly-equal-length partitions [duplicate]将列表切成n个几乎相等长度的分区[重复]
【发布时间】:2011-02-09 05:38:18
【问题描述】:

我正在寻找一种快速、干净、pythonic 的方法来将列表划分为 n 个几乎相等的分区。

partition([1,2,3,4,5],5)->[[1],[2],[3],[4],[5]]
partition([1,2,3,4,5],2)->[[1,2],[3,4,5]] (or [[1,2,3],[4,5]])
partition([1,2,3,4,5],3)->[[1,2],[3,4],[5]] (there are other ways to slice this one too)

这里有几个答案Iteration over list slices 非常接近我想要的,除了他们关注列表的size,我关心number em> 列表(其中一些也用 None 填充)。显然,这些转换很简单,但我正在寻找最佳实践。

同样,人们在How do you split a list into evenly sized chunks? 为一个非常相似的问题指出了很好的解决方案,但我更感兴趣的是分区的数量而不是具体的大小,只要它在 1 以内。同样,这很容易转换,但我正在寻找最佳做法。

【问题讨论】:

    标签: python list slice


    【解决方案1】:
    def partition(lst, n):
        division = len(lst) / float(n)
        return [ lst[int(round(division * i)): int(round(division * (i + 1)))] for i in xrange(n) ]
    
    >>> partition([1,2,3,4,5],5)
    [[1], [2], [3], [4], [5]]
    >>> partition([1,2,3,4,5],2)
    [[1, 2, 3], [4, 5]]
    >>> partition([1,2,3,4,5],3)
    [[1, 2], [3, 4], [5]]
    >>> partition(range(105), 10)
    [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20], [21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31], [32, 33, 34, 35, 36, 37, 38, 39, 40, 41], [42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52], [53, 54, 55, 56, 57, 58, 59, 60, 61, 62], [63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73], [74, 75, 76, 77, 78, 79, 80, 81, 82, 83], [84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94], [95, 96, 97, 98, 99, 100, 101, 102, 103, 104]]
    

    Python 3 版本:

    def partition(lst, n):
        division = len(lst) / n
        return [lst[round(division * i):round(division * (i + 1))] for i in range(n)]
    

    【讨论】:

    • 这不适用于重要的示例。对于partition(range(105), 10),最后一个子列表将只有 6 个元素。
    • 您将如何拆分该列表?
    • @JG: 10个项目的5个子列表和11个项目的5个子列表。
    • @Daniel:很公平,尽管在最初的问题中并不是很清楚。现在已经“修复”了。
    • @JG:我相信“n 几乎相等”的意思是“n 的长度几乎相等”; “只要在 1 以内”也是一个强烈的暗示,即使是模糊不清的。
    【解决方案2】:

    这个答案提供了一个函数split(list_, n, max_ratio),供人们使用 谁想要将他们的列表分成n 块,最多max_ratio 片长的比例。它允许比 提问者的“片段长度最多相差 1”。

    它通过在所需比率范围内对 n 个长度进行采样来工作 [1 , max_ratio),将它们一个接一个放置,形成一个 'broken 坚持“断点”之间的正确距离,但错误 总长度。将折断的棍子缩放到所需的长度给我们 我们想要的断点的大致位置。获取整数 断点需要后续舍入。

    不幸的是,四舍五入可能会导致碎片太短, 让你超过max_ratio。请参阅此答案的底部以获取 例子。

    import random
    
    def splitting_points(length, n, max_ratio):
        """n+1 slice points [0, ..., length] for n random-sized slices.
    
        max_ratio is the largest allowable ratio between the largest and the
        smallest part.
        """
        ratios = [random.uniform(1, max_ratio) for _ in range(n)]
        normalized_ratios = [r / sum(ratios) for r in ratios]
        cumulative_ratios = [
            sum(normalized_ratios[0:i])
            for i in range(n+1)
        ]
        scaled_distances = [
            int(round(r * length))
            for r in cumulative_ratios
        ]
    
        return scaled_distances
    
    
    def split(list_, n, max_ratio):
        """Slice a list into n randomly-sized parts.
    
        max_ratio is the largest allowable ratio between the largest and the
        smallest part.
        """
    
        points = splitting_points(len(list_), n, ratio)
    
        return [
            list_[ points[i] : points[i+1] ]
            for i in range(n)
        ]
    

    你可以这样试试:

    for _ in range(10):
        parts = split('abcdefghijklmnopqrstuvwxyz', 4, 2)
        print([(len(part), part) for part in parts])
    

    不良结果示例:

    parts = split('abcdefghijklmnopqrstuvwxyz', 10, 2)
    
    # lengths range from 1 to 4, not 2 to 4
    [(3, 'abc'),  (3, 'def'), (1, 'g'),
     (4, 'hijk'), (3, 'lmn'), (2, 'op'),
     (2, 'qr'),  (3, 'stu'),  (2, 'vw'),
     (3, 'xyz')]
    

    【讨论】:

      【解决方案3】:

      只是一种不同的做法,仅当[[1,3,5],[2,4]] 是您的示例中可接受的分区时才有效。

      def partition ( lst, n ):
          return [ lst[i::n] for i in xrange(n) ]
      

      这满足@Daniel Stutzbach 的例子中提到的例子:

      partition(range(105),10)
      # [[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
      # [1, 11, 21, 31, 41, 51, 61, 71, 81, 91, 101],
      # [2, 12, 22, 32, 42, 52, 62, 72, 82, 92, 102],
      # [3, 13, 23, 33, 43, 53, 63, 73, 83, 93, 103],
      # [4, 14, 24, 34, 44, 54, 64, 74, 84, 94, 104],
      # [5, 15, 25, 35, 45, 55, 65, 75, 85, 95],
      # [6, 16, 26, 36, 46, 56, 66, 76, 86, 96],
      # [7, 17, 27, 37, 47, 57, 67, 77, 87, 97],
      # [8, 18, 28, 38, 48, 58, 68, 78, 88, 98],
      # [9, 19, 29, 39, 49, 59, 69, 79, 89, 99]]
      

      【讨论】:

      • 这是一个奇妙的 Python 解决方案
      • 我觉得必须有一些聪明的方法来获得原始的、所需的输入,但zip( *partition(range(105),10) ) 不起作用,因为 zip 会截断......不过,非常好。
      • 天哪,这太棒了。
      • 如果您使用 itertools.izip 的时间最长,它应该可以工作
      • 确实非常整洁(如果您不需要连续分区)。
      【解决方案4】:

      这是一个与 Daniel 类似的版本:它尽可能均匀地划分,但将所有较大的分区放在开头:

      def partition(lst, n):
          q, r = divmod(len(lst), n)
          indices = [q*i + min(i, r) for i in xrange(n+1)]
          return [lst[indices[i]:indices[i+1]] for i in xrange(n)]
      

      它还避免使用浮点运算,因为那总是让我不舒服。 :)

      编辑:一个例子,只是为了展示与 Daniel Stutzbach 的解决方案的对比

      >>> print [len(x) for x in partition(range(105), 10)]
      [11, 11, 11, 11, 11, 10, 10, 10, 10, 10]
      

      【讨论】:

        【解决方案5】:

        下面是一种方法。

        def partition(lst, n):
            increment = len(lst) / float(n)
            last = 0
            i = 1
            results = []
            while last < len(lst):
                idx = int(round(increment * i))
                results.append(lst[last:idx])
                last = idx
                i += 1
            return results
        

        如果 len(lst) 不能被 n 整除,这个版本会以大致相等的间隔分配额外的项目。例如:

        >>> print [len(x) for x in partition(range(105), 10)]
        [11, 10, 11, 10, 11, 10, 11, 10, 11, 10]
        

        如果您不介意所有 11 都在开头或结尾,那么代码可能会更简单。

        【讨论】:

        • 使用浮点可能会导致与机器相关的结果:当 increment*i (在数学上)恰好在两个整数之间的中间时,根据引入的数值错误,舍入可以采用任何一种方式.改用idx = len(lst)*i//n 之类的东西怎么样?或者idx = (len(lst)*i + n//2)//n 可能会得到类似于当前代码的结果。
        • 仅供参考,这是众所周知的Bresenham algorithm
        猜你喜欢
        • 2011-03-22
        • 2011-01-08
        • 1970-01-01
        • 2011-10-15
        • 1970-01-01
        • 1970-01-01
        • 2015-10-01
        • 2014-05-04
        • 1970-01-01
        相关资源
        最近更新 更多