Python 对象不支持索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42978738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:20:41  来源:igfitidea点击:

Object Does Not Support Indexing

pythonindexing

提问by John Rogerson

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:

我正在 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()

The error is pointing to the datesfunction 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:

错误指向下面显示的日期函数以及我的“任务列表”类的其他一些方法。我索引这个列表的方式有问题吗?或者我是对的,因为当用户进入循环的第二步时,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)

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

注意——这里是 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

Added per Jake's recommendation:

根据Hyman的建议添加:

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)

回答by Jake Conkerton-Darby

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

问题似乎出在你打电话的地方date = row[0];这是因为在循环row中将是一个Task对象,因为您正在迭代self.task_list。在这种情况下,您正在尝试对Task未设置索引的对象进行索引。

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

对此的简单解决方案是替换row[0]row.date; 它将直接访问对象的date字段,根本row不需要关心索引。