リストの要素の可能な組み合わせをすべて取得するにはどうすればよいでしょうか?

StackOverflow https://stackoverflow.com/questions/464864

  •  19-08-2019
  •  | 
  •  

質問

15 個の数値を含むリストがあり、これらの数値の 32,768 通りの組み合わせをすべて生成するコードを記述する必要があります。

見つけました いくつかのコード (グーグルで検索すると)どうやら私が探していることを実行するようですが、コードがかなり不透明であることがわかり、使用には慎重です。さらに、もっとエレガントな解決策があるはずだと私は感じています。

私が思いつく唯一のことは、10 進整数 1 ~ 32768 をループしてそれらを 2 進数に変換し、その 2 進数表現をフィルターとして使用して適切な数値を選択することです。

誰かもっと良い方法を知っていますか?使用する map(), 、 多分?

役に立ちましたか?

解決

itertools.combinations のを見てください

itertools.combinations(iterable, r)
     からの要素の

リターンR長サブ   入力反復可能ます。

     

の組み合わせは、辞書式ソート順に放出されます。だから、もし   入力反復可能でソートされ、   組み合わせのタプルがで生産されます   順番を並べ替えます。

2.6ので、電池は含まれています!

他のヒント

こちらは怠け者の一ライナー"また利用itertools:

from itertools import compress, product

def combinations(items):
    return ( set(compress(items,mask)) for mask in product(*[[0,1]]*len(items)) )
    # alternative:                      ...in product([0,1], repeat=len(items)) )

主なかこの答え:が2^Nの組み合わせ--と同じ数のバイナリ文字列の長さN各バイナリ文字列、お渡しすべての要素に対応する"1".

items=abc * mask=###
 |
 V
000 -> 
001 ->   c
010 ->  b
011 ->  bc
100 -> a
101 -> a c
110 -> ab
111 -> abc

ものを考える:

  • ることを必要と話ができ len(...)items (回避策:の場合 items あのようなものであるというのlistのように発電機では、リストにして初 items=list(_itemsArg))
  • この繰り返しに items はいランダム(回避策:なclaw)
  • この項目は独自のも {2,2,1}{2,1,1} 両社による崩壊 {2,1} (回避策:使用 collections.Counter としてのドロ set;では基本的にはmultiset...もる必要がある場以降の利用 tuple(sorted(Counter(...).elements())) 請求-お問い合わせはこちられhashable)

デモ

>>> list(combinations(range(4)))
[set(), {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}, {0}, {0, 3}, {0, 2}, {0, 2, 3}, {0, 1}, {0, 1, 3}, {0, 1, 2}, {0, 1, 2, 3}]

>>> list(combinations('abcd'))
[set(), {'d'}, {'c'}, {'c', 'd'}, {'b'}, {'b', 'd'}, {'c', 'b'}, {'c', 'b', 'd'}, {'a'}, {'a', 'd'}, {'a', 'c'}, {'a', 'c', 'd'}, {'a', 'b'}, {'a', 'b', 'd'}, {'a', 'c', 'b'}, {'a', 'c', 'b', 'd'}]

高く評価されたコメントの下で 答え @Dan H によると、 powerset() のレシピ itertools ドキュメンテーション— によるものを含む ダン自身. しかし, 、今のところ誰も回答として投稿していません。それはおそらく、問題に対する最良のアプローチではないにしても、より良いアプローチの 1 つであるため、 少しの励まし 別のコメント投稿者からのコメントを以下に示します。関数が生成するのは、 全て のリスト要素の一意の組み合わせ 可能な長さ (ゼロおよびすべての要素を含むものを含む)。

注記:微妙に異なりますが、固有の要素の組み合わせのみを取得することが目標の場合は、行を変更します。 s = list(iterable)s = list(set(iterable)) 重複した要素を削除します。それにもかかわらず、その事実は、 iterable 最終的には list (他のいくつかの回答とは異なり) ジェネレーターで動作することを意味します。

from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)  # allows duplicate elements
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

stuff = [1, 2, 3]
for i, combo in enumerate(powerset(stuff), 1):
    print('combo #{}: {}'.format(i, combo))

出力:

combo #1: ()
combo #2: (1,)
combo #3: (2,)
combo #4: (3,)
combo #5: (1, 2)
combo #6: (1, 3)
combo #7: (2, 3)
combo #8: (1, 2, 3)

ここで再帰を使用していずれかになります。

>>> import copy
>>> def combinations(target,data):
...     for i in range(len(data)):
...         new_target = copy.copy(target)
...         new_data = copy.copy(data)
...         new_target.append(data[i])
...         new_data = data[i+1:]
...         print new_target
...         combinations(new_target,
...                      new_data)
...                      
... 
>>> target = []
>>> data = ['a','b','c','d']
>>> 
>>> combinations(target,data)
['a']
['a', 'b']
['a', 'b', 'c']
['a', 'b', 'c', 'd']
['a', 'b', 'd']
['a', 'c']
['a', 'c', 'd']
['a', 'd']
['b']
['b', 'c']
['b', 'c', 'd']
['b', 'd']
['c']
['c', 'd']
['d']

このワンライナーは、(元のリスト/セットが0個別の要素が含まれている場合nitertools.combinations項目間の)あなたのすべての組み合わせを提供し、ネイティブメソッド<のhref = "httpsを使用しています://ドキュメントを.python.org / 2 /ライブラリ/ itertools.html#のitertools.combinations」のrel = "noreferrer"> <=> のます:

Pythonの2

from itertools import combinations

input = ['a', 'b', 'c', 'd']

output = sum([map(list, combinations(input, i)) for i in range(len(input) + 1)], [])

Pythonの3

from itertools import combinations

input = ['a', 'b', 'c', 'd']

output = sum([list(map(list, combinations(input, i))) for i in range(len(input) + 1)], [])
<時間>

出力は次のようになります。

[[],
 ['a'],
 ['b'],
 ['c'],
 ['d'],
 ['a', 'b'],
 ['a', 'c'],
 ['a', 'd'],
 ['b', 'c'],
 ['b', 'd'],
 ['c', 'd'],
 ['a', 'b', 'c'],
 ['a', 'b', 'd'],
 ['a', 'c', 'd'],
 ['b', 'c', 'd'],
 ['a', 'b', 'c', 'd']]
<時間>

オンラインそれを試してみます:

http://ideone.com/COghfXする

私はベンが実際のすべての組み合わせを求めていることダン・Hに同意します。 itertools.combinations()すべての組み合わせを与えるものではありません。

入力が反復可能が大きい場合は、

もう一つの問題は、代わりに、リスト内のすべての発電機を返すために、おそらくより良いです。

iterable = range(10)
for s in xrange(len(iterable)+1):
  for comb in itertools.combinations(iterable, s):
    yield comb

できる発電を組み合わせリストにpythonのこのこコード

import itertools

a = [1,2,3,4]
for i in xrange(0,len(a)+1):
   print list(itertools.combinations(a,i))

をとるという結果:

[()]
[(1,), (2,), (3,), (4,)]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]
[(1, 2, 3, 4)]

私はitertoolsや他の余分なライブラリをインポートせずに答えを求める方のために、この機能を追加するだろうと思っています。

def powerSet(items):
    """
    Power set generator: get all possible combinations of a list’s elements

    Input:
        items is a list
    Output:
        returns 2**n combination lists one at a time using a generator 

    Reference: edx.org 6.00.2x Lecture 2 - Decision Trees and dynamic programming
    """

    N = len(items)
    # enumerate the 2**N possible combinations
    for i in range(2**N):
        combo = []
        for j in range(N):
            # test bit jth of integer i
            if (i >> j) % 2 == 1:
                combo.append(items[j])
        yield combo

シンプルな収量ジェネレータの使用方法:

for i in powerSet([1,2,3,4]):
    print (i, ", ",  end="")

上記の使用例からの出力

  

[]、[1]、[2]、[1、2]、[3]、[1,3]、[2,3]、[1、2、3]、[4]   [1,4]、[2,4]、[1、2、4]、[3,4]、[1,3]、[4]、[2、3、4]、[1、2、   3、4]、

ここでは、まだitertools.combinations機能を使用して関与する別の溶液(ワンライナー)、であるが、ここでは(ループまたは合計のためにではなく)私たちは、二重リストの内包表記を使用します:

def combs(x):
    return [c for i in range(len(x)+1) for c in combinations(x,i)]
<時間>

デモます:

>>> combs([1,2,3,4])
[(), 
 (1,), (2,), (3,), (4,), 
 (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), 
 (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4), 
 (1, 2, 3, 4)]

これは容易に再帰の(NO itertools、無収率、なしリスト内包)をサポートするすべてのプログラミング言語に転送することができるアプローチである

def combs(a):
    if len(a) == 0:
        return [[]]
    cs = []
    for c in combs(a[1:]):
        cs += [c, c+[a[0]]]
    return cs

>>> combs([1,2,3,4,5])
[[], [1], [2], [2, 1], [3], [3, 1], [3, 2], ..., [5, 4, 3, 2, 1]]

でも使用できないitertools

のための組

このメソッドではリストとして入力を返しオブジェクトのリストタプルが含まれる順列の長さL一覧です。

# A Python program to print all  
# permutations of given length 
from itertools import permutations 

# Get all permutations of length 2 
# and length 2 
perm = permutations([1, 2, 3], 2) 

# Print the obtained permutations 
for i in list(perm): 
    print (i) 

組み合わせ

このメソッドではリストには入力と入力して返しオブジェクトのリストタプルを含む全ての可能な組み合わせの長r一覧です。

# A Python program to print all  
# combinations of given length 
from itertools import combinations 

# Get all combinations of [1, 2, 3] 
# and length 2 
comb = combinations([1, 2, 3], 2) 

# Print the obtained combinations 
for i in list(comb): 
    print (i) 

この

以下は、他の同様の答え https://stackoverflow.com/a/23743696/と同様に、「標準の再帰的な答え」であります711085 に。 (私たちは!順列を全てNを処理できる方法はありませんので、私たちは現実的にスタック領域の不足を心配する必要はありません。)

これは、順番にすべての要素を訪問し、どちらか(私たちは直接、このアルゴリズムから2 ^ Nのカーディナリティを見ることができます)、それを取るか、それを残しています。

def combs(xs, i=0):
    if i==len(xs):
        yield ()
        return
    for c in combs(xs,i+1):
        yield c
        yield c+(xs[i],)
<時間>

デモます:

>>> list( combs(range(5)) )
[(), (0,), (1,), (1, 0), (2,), (2, 0), (2, 1), (2, 1, 0), (3,), (3, 0), (3, 1), (3, 1, 0), (3, 2), (3, 2, 0), (3, 2, 1), (3, 2, 1, 0), (4,), (4, 0), (4, 1), (4, 1, 0), (4, 2), (4, 2, 0), (4, 2, 1), (4, 2, 1, 0), (4, 3), (4, 3, 0), (4, 3, 1), (4, 3, 1, 0), (4, 3, 2), (4, 3, 2, 0), (4, 3, 2, 1), (4, 3, 2, 1, 0)]

>>> list(sorted( combs(range(5)), key=len))
[(), 
 (0,), (1,), (2,), (3,), (4,), 
 (1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2), (4, 3), 
 (2, 1, 0), (3, 1, 0), (3, 2, 0), (3, 2, 1), (4, 1, 0), (4, 2, 0), (4, 2, 1), (4, 3, 0), (4, 3, 1), (4, 3, 2), 
 (3, 2, 1, 0), (4, 2, 1, 0), (4, 3, 1, 0), (4, 3, 2, 0), (4, 3, 2, 1), 
 (4, 3, 2, 1, 0)]

>>> len(set(combs(range(5))))
32

このコードは、ネストされたリストと単純なアルゴリズムを採用して...

# FUNCTION getCombos: To generate all combos of an input list, consider the following sets of nested lists...
#
#           [ [ [] ] ]
#           [ [ [] ], [ [A] ] ]
#           [ [ [] ], [ [A],[B] ],         [ [A,B] ] ]
#           [ [ [] ], [ [A],[B],[C] ],     [ [A,B],[A,C],[B,C] ],                   [ [A,B,C] ] ]
#           [ [ [] ], [ [A],[B],[C],[D] ], [ [A,B],[A,C],[B,C],[A,D],[B,D],[C,D] ], [ [A,B,C],[A,B,D],[A,C,D],[B,C,D] ], [ [A,B,C,D] ] ]
#
#  There is a set of lists for each number of items that will occur in a combo (including an empty set).
#  For each additional item, begin at the back of the list by adding an empty list, then taking the set of
#  lists in the previous column (e.g., in the last list, for sets of 3 items you take the existing set of
#  3-item lists and append to it additional lists created by appending the item (4) to the lists in the
#  next smallest item count set. In this case, for the three sets of 2-items in the previous list. Repeat
#  for each set of lists back to the initial list containing just the empty list.
#

def getCombos(listIn = ['A','B','C','D','E','F'] ):
    listCombos = [ [ [] ] ]     # list of lists of combos, seeded with a list containing only the empty list
    listSimple = []             # list to contain the final returned list of items (e.g., characters)

    for item in listIn:
        listCombos.append([])   # append an emtpy list to the end for each new item added
        for index in xrange(len(listCombos)-1, 0, -1):  # set the index range to work through the list
            for listPrev in listCombos[index-1]:        # retrieve the lists from the previous column
                listCur = listPrev[:]                   # create a new temporary list object to update
                listCur.append(item)                    # add the item to the previous list to make it current
                listCombos[index].append(listCur)       # list length and append it to the current list

                itemCombo = ''                          # Create a str to concatenate list items into a str
                for item in listCur:                    # concatenate the members of the lists to create
                    itemCombo += item                   # create a string of items
                listSimple.append(itemCombo)            # add to the final output list

    return [listSimple, listCombos]
# END getCombos()

私はそれがのすべてのの組み合わせを取得するためにitertoolsを使用することがはるかに実用的だけど、あなたはをあなたがそう望むことが起こるならば、は、部分的にのみリスト内包でこれを達成することができ、あなたがコーディングしたい付与されたの多く

二対の組合せの場合:

    lambda l: [(a, b) for i, a in enumerate(l) for b in l[i+1:]]


そして、3組の組み合わせのために、それはこのように簡単です:

    lambda l: [(a, b, c) for i, a in enumerate(l) for ii, b in enumerate(l[i+1:]) for c in l[i+ii+2:]]


結果はitertools.combinationsを使用した場合と同じです。

import itertools
combs_3 = lambda l: [
    (a, b, c) for i, a in enumerate(l) 
    for ii, b in enumerate(l[i+1:]) 
    for c in l[i+ii+2:]
]
data = ((1, 2), 5, "a", None)
print("A:", list(itertools.combinations(data, 3)))
print("B:", combs_3(data))
# A: [((1, 2), 5, 'a'), ((1, 2), 5, None), ((1, 2), 'a', None), (5, 'a', None)]
# B: [((1, 2), 5, 'a'), ((1, 2), 5, None), ((1, 2), 'a', None), (5, 'a', None)]

itertoolsを使用しない場合:

def combine(inp):
    return combine_helper(inp, [], [])


def combine_helper(inp, temp, ans):
    for i in range(len(inp)):
        current = inp[i]
        remaining = inp[i + 1:]
        temp.append(current)
        ans.append(tuple(temp))
        combine_helper(remaining, temp, ans)
        temp.pop()
    return ans


print(combine(['a', 'b', 'c', 'd']))

ここでの2つの実装であるitertools.combinations

リストを返すワン

def combinations(lst, depth, start=0, items=[]):
    if depth <= 0:
        return [items]
    out = []
    for i in range(start, len(lst)):
        out += combinations(lst, depth - 1, i + 1, items + [lst[i]])
    return out

一つは、発電機を返します。

def combinations(lst, depth, start=0, prepend=[]):
    if depth <= 0:
        yield prepend
    else:
        for i in range(start, len(lst)):
            for c in combinations(lst, depth - 1, i + 1, prepend + [lst[i]]):
                yield c

先頭に追加引数は静的であり、

すべての呼び出しで変更されていないため、それらにヘルパー機能を提供するが助言されることに注意してください
print([c for c in combinations([1, 2, 3, 4], 3)])
# [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]

# get a hold of prepend
prepend = [c for c in combinations([], -1)][0]
prepend.append(None)

print([c for c in combinations([1, 2, 3, 4], 3)])
# [[None, 1, 2, 3], [None, 1, 2, 4], [None, 1, 3, 4], [None, 2, 3, 4]]

これは非常に表面的なケースですが、より良い後悔するより安全である。

これはどのように...リストの代わりに文字列を使用しますが、同じこと...文字列がPythonでリストのように扱うことができます:

def comb(s, res):
    if not s: return
    res.add(s)
    for i in range(0, len(s)):
        t = s[0:i] + s[i + 1:]
        comb(t, res)

res = set()
comb('game', res) 

print(res)

itertoolsからのコンビネーション

import itertools
col_names = ["aa","bb", "cc", "dd"]
all_combinations = itertools.chain(*[itertools.combinations(col_names,i+1) for i,_ in enumerate(col_names)])
print(list(all_combinations))

おかげ

なしitertoolsのPython 3に、あなたがこのような何かを行うことができます:

def combinations(arr, carry):
    for i in range(len(arr)):
        yield carry + arr[i]
        yield from combinations(arr[i + 1:], carry + arr[i])

ここで、最初に、carry = "".

リストの内包を使用します:

def selfCombine( list2Combine, length ):
    listCombined = str( ['list2Combine[i' + str( i ) + ']' for i in range( length )] ).replace( "'", '' ) \
                     + 'for i0 in range(len( list2Combine ) )'
    if length > 1:
        listCombined += str( [' for i' + str( i ) + ' in range( i' + str( i - 1 ) + ', len( list2Combine ) )' for i in range( 1, length )] )\
            .replace( "', '", ' ' )\
            .replace( "['", '' )\
            .replace( "']", '' )

    listCombined = '[' + listCombined + ']'
    listCombined = eval( listCombined )

    return listCombined

list2Combine = ['A', 'B', 'C']
listCombined = selfCombine( list2Combine, 2 )

出力は次のようになります:

['A', 'A']
['A', 'B']
['A', 'C']
['B', 'B']
['B', 'C']
['C', 'C']

これは私の実装です。

    def get_combinations(list_of_things):
    """gets every combination of things in a list returned as a list of lists

    Should be read : add all combinations of a certain size to the end of a list for every possible size in the
    the list_of_things.

    """
    list_of_combinations = [list(combinations_of_a_certain_size)
                            for possible_size_of_combinations in range(1,  len(list_of_things))
                            for combinations_of_a_certain_size in itertools.combinations(list_of_things,
                                                                                         possible_size_of_combinations)]
    return list_of_combinations
def combinations(iterable, r):
# combinations('ABCD', 2) --> AB AC AD BC BD CD
# combinations(range(4), 3) --> 012 013 023 123
pool = tuple(iterable)
n = len(pool)
if r > n:
    return
indices = range(r)
yield tuple(pool[i] for i in indices)
while True:
    for i in reversed(range(r)):
        if indices[i] != i + n - r:
            break
    else:
        return
    indices[i] += 1
    for j in range(i+1, r):
        indices[j] = indices[j-1] + 1
    yield tuple(pool[i] for i in indices)


x = [2, 3, 4, 5, 1, 6, 4, 7, 8, 3, 9]
for i in combinations(x, 2):
    print i

私がしたように、誰かが、逆のリストを探している場合:

stuff = [1, 2, 3, 4]

def reverse(bla, y):
    for subset in itertools.combinations(bla, len(bla)-y):
        print list(subset)
    if y != len(bla):
        y += 1
        reverse(bla, y)

reverse(stuff, 1)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top