【问题标题】:TypeError: list indices must be integers or slices, not str - for timetablesTypeError:列表索引必须是整数或切片,而不是 str - 用于时间表
【发布时间】:2021-03-03 20:15:53
【问题描述】:
dailyTimetable = [
        [{'Physics': '0830'}, {'Computer Science': '0915'}, {'Biology': '1000'}, {'English': '1125'}, {'History':'1210'}, {'DT':'1440'}, {'Maths': '1515'}],
        [{'French':'0830'}, {'English':'0915'}, {'DT':'1000'}, {'Chemistry':'1125'}, {'Computer Science':'1210'}],
        [{'Maths':'0830'}, {'DT':'0915'}, {'Physics':'1000'}, {'Biology':'1125'}, {'Biolody':'1210'}, {'English':'1440'}, {'History':'1515'}],
        [{'Biology':'0830'}, {'French':'0915'}, {'Maths':'1000'}, {'Computer Science':'1125'}, {'Physics':'1210'}],
        ['English', 'French', 'History', 'Computer Science', 'DT', 'Chemistry', 'Chemistry'],
        ['History', 'English', 'Physics', 'Maths','French']
            ]


class timetable:
    def __init__(self, timetable):
        self.timetable = timetable

    def getSubject(self, day, period):
        return list(self.timetable[day-1][period-1])[0]

    def getPeriod(self, day, subject):
        return list(self.timetable[day-1][subject])[1]


test = timetable(dailyTimetable)

print(test.getPeriod(1, 'Physics'))

我正在尝试制作一些获得时间表“周期”的东西,但我不知道该怎么做,这是一种尝试,但它不起作用,有人可以帮助我!

【问题讨论】:

    标签: class typeerror


    【解决方案1】:

    您收到该错误的原因是您试图从字典数组中访问键“Physics”。由于您每天都有一系列字典,因此您需要在特定日期的时段数组中搜索匹配时段,并在找到后返回。比如:

    def getPeriod(self, day, subject):
        todaysTimetable = dailyTimetable[day]
        for currentPeriod in todaysTimetable:
            if subject in currentPeriod:
                return currentPeriod[subject]
    

    【讨论】:

      猜你喜欢
      • 2015-12-09
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      • 2018-10-13
      相关资源
      最近更新 更多