Python jede Listen Möglichkeit durchlaufen lassen?


10.04.2022, 04:02

Wichtig hierbei, es sollen immer nur 2 a's in der Liste vorhanden sein. Niemals mehr oder weniger.

2 Antworten

Vom Beitragsersteller als hilfreich ausgezeichnet

Hmm, komplett vorgefertigt fällt mir im Moment gerade nichts ein. Aber ich würde das in etwa so lösen...

from itertools import combinations

l = 8*['b']
for ind in combinations(range(len(l)), 2):
    l_neu = l.copy()
    for i in ind:
        l_neu[i] = 'a'
    print(l_neu)

Oder wahrscheinlich eher so...

from itertools import combinations

l = 8*['b']
for ind in combinations(range(len(l)), 2):
    l_neu = ['a' if i in ind else ele for i, ele in enumerate(l)]
    print(l_neu)

Als Ausgabe erhält man jeweils:

['a', 'a', 'b', 'b', 'b', 'b', 'b', 'b']
['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b']
['a', 'b', 'b', 'a', 'b', 'b', 'b', 'b']
['a', 'b', 'b', 'b', 'a', 'b', 'b', 'b']
['a', 'b', 'b', 'b', 'b', 'a', 'b', 'b']
['a', 'b', 'b', 'b', 'b', 'b', 'a', 'b']
['a', 'b', 'b', 'b', 'b', 'b', 'b', 'a']
['b', 'a', 'a', 'b', 'b', 'b', 'b', 'b']
['b', 'a', 'b', 'a', 'b', 'b', 'b', 'b']
['b', 'a', 'b', 'b', 'a', 'b', 'b', 'b']
['b', 'a', 'b', 'b', 'b', 'a', 'b', 'b']
['b', 'a', 'b', 'b', 'b', 'b', 'a', 'b']
['b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
['b', 'b', 'a', 'a', 'b', 'b', 'b', 'b']
['b', 'b', 'a', 'b', 'a', 'b', 'b', 'b']
['b', 'b', 'a', 'b', 'b', 'a', 'b', 'b']
['b', 'b', 'a', 'b', 'b', 'b', 'a', 'b']
['b', 'b', 'a', 'b', 'b', 'b', 'b', 'a']
['b', 'b', 'b', 'a', 'a', 'b', 'b', 'b']
['b', 'b', 'b', 'a', 'b', 'a', 'b', 'b']
['b', 'b', 'b', 'a', 'b', 'b', 'a', 'b']
['b', 'b', 'b', 'a', 'b', 'b', 'b', 'a']
['b', 'b', 'b', 'b', 'a', 'a', 'b', 'b']
['b', 'b', 'b', 'b', 'a', 'b', 'a', 'b']
['b', 'b', 'b', 'b', 'a', 'b', 'b', 'a']
['b', 'b', 'b', 'b', 'b', 'a', 'a', 'b']
['b', 'b', 'b', 'b', 'b', 'a', 'b', 'a']
['b', 'b', 'b', 'b', 'b', 'b', 'a', 'a']

Die Idee dahinter combinations(range(len(l)), 2) liefert die Kombinationen für Positionen/Indizes der Liste, bei denen die Elemente ersetzt werden sollen. Danach muss man noch die Elemente an den entsprechenden Positionen ersetzten.


KarlRanseierIII  10.04.2022, 20:54

Die Ansätzue gefallen mir, ich hatte auch noch über itertools nachgedacht, es dann aber doch verworfen.

0
>>> l=list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> for i in range(len(l)-1):
...    tmp=l[i]
...    l[i]='a'
...    for j in range(i+1,len(l)):
...       tmp2=l[j]
...       l[j]='a'
...       print(l)
...       l[j]=tmp2
...    l[i]=tmp
...
['a', 'a', 2, 3, 4]
['a', 1, 'a', 3, 4]
['a', 1, 2, 'a', 4]
['a', 1, 2, 3, 'a']
[0, 'a', 'a', 3, 4]
[0, 'a', 2, 'a', 4]
[0, 'a', 2, 3, 'a']
[0, 1, 'a', 'a', 4]
[0, 1, 'a', 3, 'a']
[0, 1, 2, 'a', 'a']

Geht vielleicht auch in hübscher, aber nicht auf die Schnelle.