web-dev-qa-db-ja.com

リストをn個のほぼ等しい長さのパーティションにスライスする

私は、リストを正確にn個のほぼ等しいパーティションに分割するための高速でクリーンなPythonicの方法を探しています。

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)

ここにはいくつかの答えがあります リストスライスの反復サイズに焦点を当てていることを除いて、私が望むものに非常に近いものですリストの)、そして私はリストのnumberを気にします(それらのいくつかはNoneで埋められます)。これらは明らかに簡単に変換されますが、私はベストプラクティスを探しています。

同様に、人々はここで優れた解決策を指摘しています リストを均等なサイズのチャンクに分割するにはどうすればよいですか? 非常によく似た問題ですが、特定のサイズよりもパーティションの数に関心があります。 1以内である限り、これも簡単に変換できますが、ベストプラクティスを探しています。

39
Drew
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)]
21
João Silva

あなたの例では、[[1,3,5],[2,4]]が許容可能なパーティションである場合にのみ機能する別の見方です。

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

これは、@ DanielStutzbachの例で述べた例を満たしています。

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]]
28
Manuel Zubieta

これはダニエルのものに似たバージョンです:それは可能な限り均等に分割しますが、最初にすべてのより大きなパーティションを置きます:

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)]

また、浮動小数点演算の使用を回避します。これは、常に不快感を与えるためです。 :)

編集:例、DanielStutzbachのソリューションとの対比を示すためだけに

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

以下は1つの方法です。

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のすべてが最初または最後にあることを気にしない場合は、コードが単純になる可能性があります。

4

この回答は、リストをn個に分割したい人のために関数split(list_, n, max_ratio)を提供し、ピースの長さは最大でmax_ratioの比率になります。質問者の「ピースの長さの最大1つの違い」よりも多くのバリエーションが可能です。

これは、n希望の比率範囲内のピースの長さ[1、max_ratio)をサンプリングし、それらを並べて配置し、 「ブレークポイント」ですが、全長が間違っています。壊れたスティックを希望の長さにスケーリングすると、必要なブレークポイントのおおよその位置がわかります。整数のブレークポイントを取得するには、後続の丸めが必要です。

残念ながら、丸めによって共謀してピースが短すぎるため、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')]
0
Esteis