简体   繁体   中英

KeyError in python…

I build a 3D array self.QL={} and "erase" the array with 0's:

for loop0 in range(50):
    for loop1 in range(50):
        for loop2 in range(self.actions):
            self.QL[loop0, loop1, loop2] = 0

But when I run the program and try to get a value from the array, it t hrows the error:

File "Bots/QL.py", line 135, in _chooseaction
self.vQ = self.QL[state[0],state[1],a]
KeyError: (0, 63, 0)

In line 135 I have:

def _chooseaction(self, state):
    self.vQ = 0
    self.action = 0
    self.temp = -1000

        for a in range(self.actions):
         self.vQ = self.QL[state[0],state[1],a]
           if self.vQ > self.temp:
             self.temp=self.vQ
             self.action=a

          return self.action

What did I do wrong?

state[1] has the value 63, but you only initialized it with values from 0 to 49.

Which is why it says that the key (0, 63, 0) doesn't exist.

Perhaps you can use a defaultdict?

from collections import defaultdict

self.QL = defaultdict(int)

Now self.QL is basically a dict that is 0 for any values it doesn't have.

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