I have this kind of code. The problem is that 'kilpailija' is not changing for the other loop. Inside the third loop 'kilpailija' is always the first variable in the list numerot. How i can get it to change to that loop also?
k = 0
for kilpailija in numerot:
while k < len(tulokset):
for kilpailijanyt in tulokset[k]:
if kilpailija == kilpailijanyt.hae_numero():
tulos.append(kilpailijanyt.hae_tulos())
if kilpailija != kilpailijanyt.hae_numero():
tulos.append("-")
k += 1
2 Answers 2
Why use the while loop at all? You aren't using k for anything other than iteration:
for kilpailija in numerot:
# I was going to use tulos for t here, but you
# already have a variable named tulos.
for t in tulokset:
for kilpailijanyt in t:
if kilpailija == kilpailijanyt.hae_numero():
tulos.append(kilpailijanyt.hae_tulos())
if kilpailija != kilpailijanyt.hae_numero():
tulos.append("-")
Comments
You never reset k in the inner loop.
The first iteration of for kilpailija in numerot runs the while loop until k < len(tulokset). Because neither k nor len(tulokset) change for the next iteration, that test is always going to be false from there on out.
Your outer loop works just fine, it is your while statement that is then never running the inner loops. Either reset k back to 0 inside the outermost loop, or use a different condition:
for kilpailija in numerot:
k = 0
while k < len(tulokset):
for kilpailijanyt in tulokset[k]:
if kilpailija == kilpailijanyt.hae_numero():
tulos.append(kilpailijanyt.hae_tulos())
if kilpailija != kilpailijanyt.hae_numero():
tulos.append("-")
k += 1
ifstatements, why not anif elsestatement?kilpailijanyt.hae_tulos()call alters the state of thekilpailijanytobject? Of course, if it doesn't andkilpailijanyt.hae_numero()returns a consistent value, then anelsewould be great there.