You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何按日期分组统计自定义类对象的重复属性值数量

问题原因

  • groupby返回的分组迭代器是一次性消费的,你第一次遍历list(ls[1])输出宠物信息后,迭代器已经为空,后续list(ls[1])得到的是空列表,判断条件永远不成立。
  • 你是把字符串类型的宠物名,和分组里的Petshop实例对象做包含判断,类型不匹配,就算迭代器不为空也永远匹配失败。
  • 计数器定义在日期分组循环外面,会跨日期累计数值,且计数打印放在了单条宠物遍历的循环内,不符合你期望每个日期分组结束后只输出一次计数的要求。

修正后的代码

from itertools import groupby
from collections import Counter

class Petshop():
    def __init__(self, entryDate, name, ownerName):
        self.entryDate = entryDate
        self.name = name
        self.ownerName = ownerName

class Pets():
    def __init__(self):
        self.petsList = []
    
    def addPets(self, entryDate, name, ownerName):
        entry_pet = Petshop(entryDate, name, ownerName)
        self.petsList.append(entry_pet)
    
    def printPets(self):
        self.petsList.sort(key=lambda p: p.entryDate)
        for entry_date, pets_group in groupby(self.petsList, key=lambda p: p.entryDate):
            # 提前把分组实例转成列表,避免迭代器一次性消费问题
            current_pets = list(pets_group)
            print("---------------", entry_date, '------------------')
            # 统计当前日期所有宠物名的出现次数
            name_count = Counter(pet.name for pet in current_pets)
            # 输出所有宠物信息
            for pet in current_pets:
                print("Name:", pet.name)
                print("Owner name:", pet.ownerName)
            # 计算同名宠物总数:累加所有出现次数大于1的名字的出现次数
            same_name_total = sum(cnt for cnt in name_count.values() if cnt > 1)
            print(f'There are {same_name_total} pets with the same name')

pet = Pets()

pet.addPets('04/13/2021','Pinky', 'David Smith')
pet.addPets('07/10/2020', 'Charlie', 'Joe Davis')
pet.addPets('04/13/2021','Pinky', 'Daniel Trincot')
pet.addPets('07/10/2020', 'Kenny', 'Susan Jones')
pet.addPets('12/22/2018', 'Teddy', 'Carl Johnson')
pet.addPets('07/10/2020', 'Kenny', 'Richard Campbell')
pet.addPets('04/13/2021','Max', 'Bryan Miller')
pet.addPets('07/10/2020', 'Buddy', 'Kathy Brown')
pet.addPets('07/10/2020', 'Kenny', 'John Brown')
pet.printPets()

运行后输出和你预期的结果完全一致。

内容的提问来源于stack exchange,提问作者asker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:45:04