在给出客户的最新记录之前,我们需要先定义一个客户记录的数据结构,例如:
class CustomerRecord:
def __init__(self, customer_id, date, data):
self.customer_id = customer_id
self.date = date
self.data = data
然后,我们可以创建一个包含客户记录的列表,并按日期降序排序:
records = [
CustomerRecord("customer1", "2021-01-01", "data1"),
CustomerRecord("customer2", "2021-01-03", "data2"),
CustomerRecord("customer1", "2021-01-05", "data3"),
CustomerRecord("customer2", "2021-01-02", "data4"),
CustomerRecord("customer1", "2021-01-04", "data5")
]
sorted_records = sorted(records, key=lambda x: x.date, reverse=True)
接下来,我们可以使用一个字典来存储每个客户的最新记录:
latest_records = {}
for record in sorted_records:
if record.customer_id not in latest_records:
latest_records[record.customer_id] = record
最后,我们可以按客户ID打印出每个客户的最新记录:
for customer_id, record in latest_records.items():
print(f"Customer ID: {customer_id}, Latest Record: {record.data}")
这样,我们就可以按日期获取每个客户的最新记录了。
下一篇:按日期获取累计总数