本文介绍了对象不支持索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在python中创建一个工作日志,用户可以在其中输入任务或可以按日期查找任务.我的初始提示要求用户按日期输入任务或查找.如果用户从按日期查找开始,则该程序可以正常工作并显示所有日期.如果用户首先添加任务,然后按日期查找任务,则程序将显示对象不支持索引错误".我认为出于某种原因,该列表已被清空,但是我一生无法理解这种情况可能在何时何地发生.这是主要的工作日志文件:

I'm creating a work log in python where a user can enter a task or can lookup a task by date. My initial prompt asks user to either enter a task or lookup by date. If the user starts by looking up by date--the program works correctly and displays all dates. If a user starts by adding a task, and then looking up tasks by date, the program displays an 'object does not support indexing error'. I think for some reason, the list is getting emptied, but i can't for the life of me understand where or when this might be happening. Here is main worklog file:

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()

错误指向 dates 函数,下面显示了该函数以及任务列表"类的其他一些方法.我索引此列表的方式是否有问题?还是我的意思是,当用户进入循环的第二步时,task_list列表正在以某种方式重置.谢谢:

The error is pointing to the dates function which is shown below along with a few of the other methods for my 'task-list' class. Is there an issue with the way that I am indexing this list? Or am i right in that the task_list list is getting reset somehow when the user enters the second step of the loop. Thanks:

    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文件的示例:

Note--here is an example of what the work_log.csv file looks like:

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

根据Jake的推荐添加:

Added per Jake's recommendation:

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)

推荐答案

问题似乎出在您呼叫date = row[0]的地方;这是因为在循环遍历self.task_list时,循环row将是Task对象.在这种情况下,您尝试索引到未设置为建立索引的Task对象.

The issue appears to be where you call date = row[0]; this is because in the loop row will be a Task object as you are iterating over self.task_list. In this case you are trying to index into a Task object, which is not set up for indexing.

一个简单的解决方案是将row[0]替换为row.date;它将直接访问row对象的date字段,而无需费心处理所有索引.

The simple solution for this would be to replace row[0] with row.date; which will directly access the date field of the row object, without needing to bother about indexing at all.

这篇关于对象不支持索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 14:20
查看更多