Python优化:如何更高效统计多列表中电影标题的出现次数?
优化电影奖项出现次数统计代码
你的原代码存在大量重复逻辑——多次重复遍历不同列表、重复调用lower().strip()处理目标字符串。可以通过合并列表+提前预处理目标字符串的方式大幅简化代码,同时提升效率:
方案1:统计总出现次数(贴合原代码逻辑)
提前处理目标字符串避免重复计算,合并所有奖项列表后用生成器表达式统计匹配次数:
def count_awards(): target = Movie_title.lower().strip() # 合并所有奖项列表 all_nominations = SAG + oscars + NBR + ISA + GLAAD + NAACP # 统计所有匹配项的数量 total_count = sum(1 for item in all_nominations if item.lower() == target) print(total_count)
方案2:优化大列表场景(若奖项列表数据量极大)
如果你的奖项列表包含大量元素,每次遍历效率较低,可以提前将每个列表的元素转为小写并存储为集合(集合的in操作时间复杂度为O(1))。注意:此方案仅适用于统计电影出现在多少个不同奖项列表中(而非总出现次数,因为集合会自动去重):
# 提前预处理所有奖项列表(只需执行一次,建议放在函数外) lower_award_sets = [ {item.lower() for item in SAG}, {item.lower() for item in oscars}, {item.lower() for item in NBR}, {item.lower() for item in ISA}, {item.lower() for item in GLAAD}, {item.lower() for item in NAACP} ] def count_awards(): target = Movie_title.lower().strip() # 统计包含目标的列表数量 total_lists = sum(1 for s in lower_award_sets if target in s) print(total_lists)
额外优化建议
- 将
Movie_title作为函数参数传入,避免依赖全局变量,让函数更通用:def count_awards(movie_title): target = movie_title.lower().strip() all_nominations = SAG + oscars + NBR + ISA + GLAAD + NAACP total_count = sum(1 for item in all_nominations if item.lower() == target) print(total_count) - 如果需要重复调用统计函数,建议提前合并并预处理所有奖项列表为小写列表,避免每次调用都重复合并和转换:
# 全局预处理 all_nominations_lower = [item.lower() for item in SAG + oscars + NBR + ISA + GLAAD + NAACP] def count_awards(movie_title): target = movie_title.lower().strip() total_count = all_nominations_lower.count(target) print(total_count)
内容的提问来源于stack exchange,提问作者user22773694
相关产品推荐
相关产品推荐

