我试图访问包含类实例的列表的值
这就是我如何在列表中存储元素的方法。
class Slot:
def __init__(self, slot, available):
self.slot = slot
self.available = available
for i in range(rangeHours):
timeSlots.append(i)
timeSlots[i] = Slot(hours[i],free[i])这是给我一个错误的代码
for call in calls:
if call == 1:
for i in timeSlots:
if timeSlots[i].available == True:
patient[i] = Patient(timeSlots[i].slot)
timeSlots[i].available == False错误码:
如果timeSlotsi.available == True: TypeError: list索引必须是整数或片,而不是插槽
谢谢你的帮助。
发布于 2019-05-14 18:39:34
你应该用一个迪克特而不是一个列表。您也可以将列表用于相同的目的,但不能使用您构造代码的方式。为什么?让我们详细看看您正在做什么:
# Lets say you have an empty list:
time_slots = []循环遍历整数并将它们附加到列表中:
for i in range(rangeHours):
time_slots.append(i)在第一次迭代之后,您将列出以下内容:
# time_slots = [0]然后,您将访问刚才附加的相同元素,将其用作索引:
# time_slots[0] = 0 , which in this case, the element you accessed is 0然后将此元素更改为槽类:
# time_slots[0] = Slot(hours[0],free[0])它直接覆盖了你刚才放在列表中的内容。总之,time_slots.append(i)没有作用。
我觉得你应该用个词来代替:
time_slots = {}
for i in range(rangeHours):
time_slots[i] = Slot(hours[i],free[i])然后你就可以:
for call in calls:
if call == 1:
for slot_index, slot_class in time_slots.items():
if slot_class.available == True:
patient[slot_index] = Patient(slot_class.slot)
slot_class.available == Falsehttps://stackoverflow.com/questions/56136389
复制相似问题