[英]TypeError: list indices must be integers or slices, not Slot
I am trying to access values of a list containing instances of a Class 我正在尝试访问包含类实例的列表的值
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
if timeSlots[i].available == True: TypeError: list indices must be integers or slices, not Slot 如果timeSlots [i] .available == True:TypeError:列表索引必须是整数或切片,而不是Slot
Thank you for your help. 谢谢您的帮助。
You should use a dict instead of a list . 您应该使用字典而不是列表 。 You can also use a list for the same purpose, but not the way you structured your code.
您也可以出于相同目的使用列表 ,但不能出于结构化代码的目的。 Why?
为什么? Let's see in detail what you are doing:
让我们详细了解您在做什么:
# Lets say you have an empty list:
time_slots = []
You loop through integers and append them into your list: 您遍历整数并将其附加到列表中:
for i in range(rangeHours):
time_slots.append(i)
After the first iteration, you list will be: 第一次迭代后,您将列出:
# time_slots = [0]
Then you are accessing the same element you have just appended using it as index: 然后,您将访问刚刚使用它作为索引附加的同一元素:
# time_slots[0] = 0 , which in this case, the element you accessed is 0
Then you change this element to be your Slot class: 然后,将此元素更改为Slot类:
# time_slots[0] = Slot(hours[0],free[0])
Which directly overwrites what you have just put into your list. 这将直接覆盖您刚刚放入列表中的内容。 In short, time_slots.append(i) has no effect.
简而言之,time_slots.append(i)无效。
I think you should use a dict instead: 我认为您应该改用dict :
time_slots = {}
for i in range(rangeHours):
time_slots[i] = Slot(hours[i],free[i])
Then you can do: 然后,您可以执行以下操作:
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 == False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.