繁体   English   中英

对包含具有日期时间属性的对象的列表进行排序

[英]Sort a list containing objects that have datetime attributes

我有 excel 文件,其中包含有关学生考试成绩的数据,他们最多可以参加 3 次考试,但我需要我的程序来识别他们参加考试的顺序,并且 excel 文件不按顺序排列。 我有一个Student class,其中包含代表所有学生尝试的对象列表和一个Attempt class,其中包括分数和参加测试的日期/时间。

import datetime as dt

class Student:
    def __init__(self, last_name, first_name ):
        self.first_name = first_name
        self.last_name = last_name

        # will hold Attempt objects that consist of score and date/time test taken
        self.attempts = []

    # I imagine I need something like this
    def order_attempts(self):
        for attempt in self.attempts:
            # compare attempt.date_and_time_of_attempt to next attempt and switch if needed/create a new Student.ordered_attempts attribute?

class Attempt:
    def __init__(self, score_as_fraction, datetime_obj):
        self.score_as_fraction = score_as_fraction
        self.date_and_time_of_attempt = datetime_obj

在我的 main.py 中,跳过 excel 中的所有数据抓取和拆分,我循环遍历每一行并构建这些对象:

import datetime as dt
datetime_obj = dt.datetime(int(year), int(month), int(day), int(hour), int(minute))
attempt_obj = Attempt(score_as_fraction, datetime_obj)
student_obj.attempts.append(attempt_obj)

So say after reading one excel file one student took the test 3 times so an imaginary student_obj.attempts = [<attempt.Attempt object at 0x105294da0>, <attempt.Attempt object at 0x102431c50>,<attempt.Attempt object at 0x105294f28>] exists但该列表按 excel 文件的顺序排列,而不是按尝试时间排列。 有没有办法从第一次尝试到最后一次尝试重新排序这个attempts列表? 我会展示我尝试过的东西,但老实说,我不确定要尝试什么。 我想我包含了所有必要的信息,但如果您需要更多信息,请告诉我。 谢谢你的帮助。

您可以简单地使用尝试 object 的date_and_time_of_attempt属性作为排序键

self.attempts.sort(key = lambda attempt: attempt.date_and_time_of_attempt)

使用您发布的代码,并提到您将传递一个 excel 文件,您无法仅通过您发布的代码来做到这一点。 您必须实际阅读 excel 文件并捕获这些日期时间 obj 值。 但是,如果您从发布的内容中获取实际的日期时间对象,您可以简单地使用list.sort()对对象列表进行排序

import datetime

yesterday = datetime.date.today() - datetime.timedelta(days=1)
today = datetime.date.today()
tomorrow = datetime.date.today() + datetime.timedelta(days=1)

date_list =[today, tomorrow, yesterday]
print(date_list)

在此处输入图像描述

date_list.sort()
print(date_list)

在此处输入图像描述

我建议像我添加的那样对尝试进行表示。 您可以使用键对任何类型的列表进行排序。 为了获得对尝试进行排序的“键”,我想告诉sorted方法,尝试由其日期时间表示。 因此,使用lambda ,我们可以做到这一点。 谷歌搜索这些术语会得到你想要的。 这是一个示例代码:

from datetime import date,datetime,timedelta

class Student:
    def __init__(self, last_name, first_name ):
        self.first_name = first_name
        self.last_name = last_name

        # will hold Attempt objects that consist of score and date/time test taken
        self.attempts = []

    # I imagine I need something like this
    def order_attempts(self):
        self.attempts = sorted(self.attempts,key= lambda attempt:attempt.date_and_time_of_attempt)

class Attempt:
    def __init__(self, score_as_fraction, datetime_obj):
        self.score_as_fraction = score_as_fraction
        self.date_and_time_of_attempt = datetime_obj
    def __repr__(self):
        return str(self.date_and_time_of_attempt)+': '+str(self.score_as_fraction)

student = Student('Doe','John')
student.attempts=[Attempt(0.8,date.today()), Attempt(0.7,date.today() + timedelta(days=1)), Attempt(0.6,date.today() - timedelta(days=1))]
print(student.attempts)
student.order_attempts()
print(student.attempts)

给予:

[2021-03-05: 0.8, 2021-03-06: 0.7, 2021-03-04: 0.6]
[2021-03-04: 0.6, 2021-03-05: 0.8, 2021-03-06: 0.7]

我认为问题实际上是如何对尝试的实例进行排序。 您可以通过添加方法__lt__使 Class 尝试可排序来做到这一点,请参见下面的示例。

from datetime import datetime

class Student:

    def __init__(self, name, attempts):
        self.name = name
        self.attempts = attempts

    def order_attempts(self, reverse=False):
        self.attemtps = attempts.sort(reverse=reverse)

class Attempt:

    def __init__(self, topic, attempt_date, score):
        self.score = score
        self.attempt_date = attempt_date
        self.topic = topic

    def __lt__(self, other):
        return self.attempt_date < other.attempt_date

    def __repr__(self):
        return f'{self.attempt_date.date()}: {self.score}'

attempts = []
attempts.append(Attempt('Math', datetime(2021, 2, 3), 4))
attempts.append(Attempt('Math', datetime(2021, 2, 5), 5))
attempts.append(Attempt('Math', datetime(2021, 2, 7), 8))
stud2 = Student('Mike Owen', attempts)

stud2.order_attempts()
print(stud2.attempts)
stud2.order_attempts(reverse=True)
print(stud2.attempts)
[2021-02-03: 4, 2021-02-05: 5, 2021-02-07: 8]
[2021-02-07: 8, 2021-02-05: 5, 2021-02-03: 4]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM