对象不支持索引

时间:2017-03-23 14:19:11

标签: python indexing

我在python中创建工作日志,用户可以在其中输入任务或按日期查找任务。我的初始提示要求用户输入任务或按日期查找。如果用户通过按日期查找开始 - 程序正常工作并显示所有日期。如果用户通过添加任务开始,然后按日期查找任务,程序将显示“对象不支持索引错误”。我认为由于某种原因,该清单正在被清空,但我不能为我的生活了解这可能发生的地点或时间。这是主要的工作日志文件:

import csv
import re
import datetime
from task import Task
from task_list import TaskList


class Worklog():
    def __init__(self):
        self.filename = "work_log.csv"
        self.tasklist = TaskList()
        self.tasklist.read_task_from_file(self.filename)

    def search_by_date(self):
        for d, i in enumerate(self.tasklist.dates()):
            print(d+1, ':', i)
        # while True:
        #     datereq = input("Select Number To See Tasks For A Date").strip().lower()
        #     try:
        #         datereq = int(datereq)
        #         return datereq
        #     except ValueError:
        #         print("Invalid Entry. Please try again")
        #         continue

    def search_by_time(self):
        pass

    def exact_search(self):
        pass

    def pattern_search(self):
        pass

    def add_task(self):
        task = Task()
        task.input_task()
        task.input_minutes()
        task.input_notes()
        task.date = datetime.date.today()
        self.tasklist.app_task(task)
        self.tasklist.save_task_to_file(self.filename,task)

    def lookup_task(self):
        if len(self.tasklist.task_list) == 0:
            print("Your task log is empty.\n")
            input("Hit Enter to add a new task.")
        else:
            while True:
                lookup = input("Lookup by Date(D), Time(T), Exact Search(E) or Pattern(P): ")
                lookup.lower()

                if lookup == 'd':
                    self.search_by_date()
                    break
                elif lookup == 't':
                    self.search_by_time()
                    break
                elif lookup == 'e':
                    self.exact_search()
                    break
                elif lookup == 'p':
                    self.pattern_search()
                    break
                else:
                    print("Sorry invalid option. Please try again")

    def start_message(self):
        while True:

            q = input("Add New Task(1) or Lookup Task(2) or Quit(3): ".strip().lower())

            if q == "1":
                self.add_task()

            elif q == "2":
                self.lookup_task()

            elif q == "3":
                exit()

            else:
                print("Sorry that's an invalid entry. Please try again.")
                continue

if __name__ == '__main__':
    log = Worklog()
    log.start_message()

错误指向 date 函数,如下所示,以及我的'task-list'类的一些其他方法。我正在索引此列表的方式是否存在问题?或者我是正确的,当用户进入循环的第二步时,task_list列表会以某种方式重置。感谢:

    def app_task(self, task):
        self.task_list.append(task)

    def save_task_to_file(self,filename,task):
        with open(filename, 'a', newline="\n", encoding="utf-8") as csvfile:
            # creating a csv writer object
            csvwriter = csv.writer(csvfile, delimiter=",")
            # writing the data rows
            csvwriter.writerow([task.date, task.task, task.minutes, task.notes])

    def read_task_from_file(self,filename):
        with open(filename, 'r') as csvfile:
            task_reader = csv.reader(csvfile, delimiter=',')
            for row in task_reader:
                task = Task()
                self.task_list.append(row)
        return self.task_list

    def dates(self):
        self.read_task_from_file("work_log.csv")
        dates = []
        for row in self.task_list:
            date = row[0]
            if row[0] not in dates:
                dates.append(date)
        return sorted(dates)

注意 - 这是work_log.csv文件的示例:

2017-03-23,gardening,30,not really
2017-03-23,bowling,30,none
2017-03-23,bowling,90,none
2017-03-23,bowling,93,none
2017-03-23,baseball,2,none
2017-03-23,bowling,20,none
2017-03-23,base,0,jj
2017-03-23,bowling,33,none

根据杰克的建议添加:

def get_date(self):
        for row in self.task_list:
            d = row[0]
            return d

    def dates(self):
        dates = []
        for row in dates:
            date = row.get_date()
            if date not in dates:
                dates.append(date)
        return sorted(dates)

1 个答案:

答案 0 :(得分:3)

问题似乎是您致电Observable<number>的地方;这是因为在迭代response: StripeCardTokenResponse时,循环date = row[0]将成为row对象。在这种情况下,您尝试索引到Task对象,该对象未设置为索引。

这方面的简单解决方案是将self.task_list替换为Task;它将直接访问row[0]对象的row.date字段,而无需为索引编制索引。