2016-08-01 35 views
0

Ich möchte einige Kombinationen aller 160 Elemente in meiner Liste machen, aber ich möchte nicht alle möglichen Kombinationen machen oder es wird nie enden. Ich will nur etwas, sagen wir 1,2,3,4.Wie man Kombinationen nCr von x bis y (nCx -nCy) macht

Statt einer nach dem anderen zu tun:

combination = itertools.combinations(lst, 1) 
combination = itertools.combinations(lst, 2) 
combination = itertools.combinations(lst, 3) 
combination = itertools.combinations(lst, 4) 

Wie kann ich alle 4 tun ???

+0

Mögliche doppelte von [Generieren aller Kombinationen einer Liste in Python] (http://stackoverflow.co m/questions/17434070/Generieren-alle-Kombinationen-einer-Liste-in-Python) – MikeJRamsey56

Antwort

0

Wie über diese einfache for Schleife:

comb = [] 
for i in range (1,5): # (start, end + 1) 
    comb[i] = itertools.combinations(lst, i) 
+0

Ich bekomme IndexError: Liste Zuordnungsindex außerhalb des Bereichs –

0

Sie einzelne Iterator erstellen können alle Kombinationen mit itertools.chain.from_iterable enthalten:

combination = chain.from_iterable(combinations(lst, i) for i in range(1,5)) 

Beispiel mit kürzeren Eingang:

>>> list(chain.from_iterable(combinations(range(3), i) for i in range(1,3))) 
[(0,), (1,), (2,), (0, 1), (0, 2), (1, 2)]