簡體   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