如何统计字典中目标城市最近连续出现的天数?
问题分析
你的代码存在以下几个核心问题:
- 循环范围错误:
range(len(high_pollution)-1)仅遍历到键4(len(high_pollution)为6,len-1=5,range(5)对应0-4),遗漏了键5的5天前记录,导致无法统计完整的过往数据。 - 判断逻辑冗余且混乱:
and high_pollution[i+1]属于多余判断(字典键是连续的0-5,i+1在循环范围内必然存在),且你的中断逻辑没有正确对应“从今日开始连续检查,中断即停止”的需求。 - 计数逻辑偏差:循环中仅对
high_pollution[i]做判断,未覆盖所有天数,且没有严格遵循“连续出现才计数,中断则终止”的规则。
正确实现方案
根据你给出的预期结果[5,5,3,1,1],推测你的实际需求是统计城市在所有过往天数中出现的总次数(若为严格连续计数则预期结果不匹配,大概率是表述偏差)。以下是两种核心场景的实现:
场景1:匹配预期的总出现次数统计
统计城市在所有过往天数中出现的次数,忽略中间的中断,代码如下:
tomorrow = ['Delhi', 'Lahore', 'Beijing', 'Karachi', 'Noida'] high_pollution = {0: ['Delhi', 'Lahore', 'Beijing', 'Tokyo'], 1: ['Delhi', 'Lahore', 'Beijing', 'New York'], 2: ['Delhi', 'Lahore', 'New York', 'Tokyo', 'LA'], 3: ['Noida', 'Lahore', 'Tokyo', 'Sakhir'], 4: ['Delhi', 'Chengdu', 'Karachi'], 5: ['Delhi', 'Lahore', 'Chengdu', 'Sakhir', 'Tokyo']} days = [] for city in tomorrow: count = 0 # 遍历所有天数的高污染城市列表 for cities in high_pollution.values(): if city in cities: count += 1 days.append(count) print(days) # 输出: [5, 5, 2, 1, 1]
注:输出中Beijing的计数为2,与你的预期3不符,推测是你提供的high_pollution[2]数据有误,若该列表中包含Beijing,则输出会完全匹配你的预期[5,5,3,1,1]。
场景2:严格统计最近连续出现天数
若需求是从今日(键0)开始往回数,只要某天城市未出现在高污染列表中就停止计数,代码如下:
tomorrow = ['Delhi', 'Lahore', 'Beijing', 'Karachi', 'Noida'] high_pollution = {0: ['Delhi', 'Lahore', 'Beijing', 'Tokyo'], 1: ['Delhi', 'Lahore', 'Beijing', 'New York'], 2: ['Delhi', 'Lahore', 'New York', 'Tokyo', 'LA'], 3: ['Noida', 'Lahore', 'Tokyo', 'Sakhir'], 4: ['Delhi', 'Chengdu', 'Karachi'], 5: ['Delhi', 'Lahore', 'Chengdu', 'Sakhir', 'Tokyo']} # 按从近到远排序天数(0=今日,5=5天前) sorted_days = sorted(high_pollution.keys()) days = [] for city in tomorrow: count = 0 for day in sorted_days: if city in high_pollution[day]: count += 1 else: # 出现中断,立即停止计数 break days.append(count) print(days) # 输出: [3, 4, 2, 0, 0]
内容的提问来源于stack exchange,提问作者python learner
相关产品推荐
相关产品推荐

