Ошибка IndexError: list index out of range
Имею код
import random
import numpy as np
class people:
__slots__ = "name", "age", "gold", "ids", "location"
def __init__(self, ids, name, age, gold, location):
self.ids = ids
self.name = name
self.age = age
self.gold = gold
self.location = location
def __str__(self):
return "ID: {} | Имя: {} | Возраст: {} | Денег: {} | Локация: {}".format(self.ids, self.name, self.age,
self.gold, self.location)
__repr__ = __str__
def getLocation(): # *проблемное место*
loca = random.randint(0, len(location))
locaPeople[loca] += 1
return location[loca]
location = [f"Место_{i}" for i in range(10)] # нужно.
locaPeople = [0 for i in range(len(location))]
pepl = [people(i, f"Человек_{i}", random.randint(18, 90), random.randint(1, 1000), getLocation()) for i in range(500000)]
из за чего происходить ошибка IndexError: list index out of range?
И как можно её исправить?
Ответы (1 шт):
Автор решения: entithat
→ Ссылка
Т.к. randint генерирует число в границах: a <= randint() <= b, то есть вероятность, что будет снегерировано число b. А элемента под таким индексом не существует. Поэтому нам надо подвинуть правую границу на -1, так loca = random.randint(0, len(location) - 1)
import random
import numpy as np
class people:
__slots__ = "name", "age", "gold", "ids", "location"
def __init__(self, ids, name, age, gold, location):
self.ids = ids
self.name = name
self.age = age
self.gold = gold
self.location = location
def __str__(self):
return "ID: {} | Имя: {} | Возраст: {} | Денег: {} | Локация: {}".format(self.ids, self.name, self.age,
self.gold, self.location)
__repr__ = __str__
def getLocation(): # *проблемное место*
loca = random.randint(0, len(location) - 1) # изменил
locaPeople[loca] += 1
return location[loca]
location = [f"Место_{i}" for i in range(10)] # нужно.
locaPeople = [0 for i in range(len(location))]
pepl = [people(i, f"Человек_{i}", random.randint(18, 90), random.randint(1, 1000), getLocation()) for i in range(500000)]