2016-07-10 5 views
1

Gibt es idiomatische Python Weg, um alle Kombinationen der spezifischen Größe aus einer Liste aufzulisten?Python-Äquivalent für Ruby-Kombinationsmethode

Der folgende Code funktioniert in Ruby (here), frage ich mich, ob es Python Äquivalent dafür ist:

a = [1, 2, 3, 4] 
a.combination(1).to_a #=> [[1],[2],[3],[4]] 
a.combination(2).to_a #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]] 
a.combination(3).to_a #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]] 

PS: Ich bin nicht für Permutationen suchen, sondern Kombinationen von bestimmten Größe.

Vielen Dank:)

Antwort

5

The itertools module has a combinations Methode, die dies für Sie tut.

itertools.combinations(a, len) 

Demo:

>>> a = [1, 2, 3, 4] 
>>> import itertools 
>>> itertools.combinations(a, 2) 
<itertools.combinations object at 0x109c276d8> 
>>> list(itertools.combinations(a, 2)) 
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] 
>>> list(itertools.combinations(a, 3)) 
[(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)] 
>>> list(itertools.combinations(a, 4)) 
[(1, 2, 3, 4)] 
+0

Vielen Dank .. Verstanden. Perfekt, wie ich es erwartet habe, werde ich deine Antwort akzeptieren. –

+0

Froh, dass es geholfen hat .. – karthikr

Verwandte Themen