簡體   English   中英

查找所有可能的垃圾箱組合

[英]Finding all possible bin combinations

我有100.000個觀察值, age在18-80之間不等。 我想根據age變量找到X垃圾箱。 檔位范圍不得重疊,並且應組合成整個間隔。 例如,當X = 4一種可能的箱組合可能是:

  • 18-30
  • 31-45
  • 46-57
  • 58-80

如何找到給定值X所有可能的垃圾箱組合?

編輯: @Wolf提示,這是我正在考慮實現自己的另一個約束。 每個垃圾箱必須至少保留10個age變量值。 那當然限制了X所以X <= 6

我嘗試將其整合到@ mkrieger1的答案中,但失敗了。

def bin_combinations(values, n):
    """
    Generate all possible combinations of splitting the values into n
    contiguous parts.

    >>> list(bin_combinations('abcd', 3))
    [['a', 'b', 'cd'], ['a', 'bc', 'd'], ['ab', 'c', 'd']]
    """

    for indices in combinations(range(1, len(values)), n - 1):
        li = list(indices)
        starts = [None] + li
        ends = li + [None]
        size = li[-1] - li[0]
        if size >= 10:
            yield [values[start:end] for start, end in zip(starts, ends)]

最合適的是,您可以使用itertools標准庫模塊中的combinations功能找到組合。

from itertools import combinations

def bin_combinations(values, n):
    """
    Generate all possible combinations of splitting the values into n
    contiguous parts.

    >>> list(bin_combinations('abcd', 3))
    [['a', 'b', 'cd'], ['a', 'bc', 'd'], ['ab', 'c', 'd']]
    """
    for indices in combinations(range(1, len(values)), n - 1):
        starts = [None] + list(indices)
        ends = list(indices) + [None]
        yield [values[start:end] for start, end in zip(starts, ends)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM