简体   繁体   中英

for with a variable list

from random import shuffle
k = 1000
T = 0
while k!=0:
    ludzie = [i for i in range(1000)]
    plaszcze = [i for i in range(1000)]
    shuffle(plaszcze)
    for value in range(k):
        if ludzie[value]==plaszcze[value]:
            k = k - 1
            del(ludzie[value])
            del(plaszcze[value])
    T = T + 1
print(T)

I'd like the first time I've done the loop, the people list was an updated list with del used earlier, the same for the coat list. Then when we use the loop the second time, it would compare the updated people with coats.

And unfortunately an error pops up.

Traceback (most recent call last):
File "", line 9, in <module>
if ludzie[value]==plaszcze[value]:
IndexError: list index out of range.

that makes sense. imagine this:

a = [1, 2, 3]
b = [3, 2, 1]

for i in range(3):
    if a[i] == b[i]:
       del a[i]
       del b[i]

what happens when i == 2 ? answer, you try to access a[2] which no longer exists because you've shortened the list.

the thing is that you don't even need to delete these values. it serves no purpose other than to break your code. get rid of the 2 del s and it'll be fine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM