Python开发喜爱类型投票应用统计结果异常求助
问题排查与解决方案
核心错误原因
- 你代码中
Horror = Romance = Comedy = History = Adventure = Action = []的写法是错误的:Python中这种连续赋值会让所有类型变量指向同一个列表对象,你往任意一个类型列表里追加用户名,本质都是往同一个列表加数据,所以最终所有列表长度都是总投票数12,和你观察到的现象完全吻合。 - 额外不规范点:不要用
str、重复的i这类Python内置名/重复循环变量名,容易引发隐性问题。
修复后的代码
num = int(input()) # 每个类型单独初始化空列表,避免指向同一对象 Horror = [] Romance = [] Comedy = [] History = [] Adventure = [] Action = [] for _ in range(num): line = input() parts = line.split() username = parts[0] for genre in parts[1:]: if genre == "Horror": Horror.append(username) elif genre == "Romance": Romance.append(username) elif genre == "Comedy": Comedy.append(username) elif genre == "History": History.append(username) elif genre == "Adventure": Adventure.append(username) elif genre == "Action": Action.append(username) # 按要求格式输出 print(f"Action : {len(Action)}") print(f"Comedy : {len(Comedy)}") print(f"History : {len(History)}") print(f"Horror : {len(Horror)}") print(f"Romance : {len(Romance)}") print(f"Adventure : {len(Adventure)}")
优化方案(可选)
用字典存储类型和对应列表,可大幅减少重复的if判断,代码更简洁易维护:
num = int(input()) genre_map = { 'Action': [], 'Comedy': [], 'History': [], 'Horror': [], 'Romance': [], 'Adventure': [] } for _ in range(num): parts = input().split() username = parts[0] for genre in parts[1:]: if genre in genre_map: genre_map[genre].append(username) # 按要求顺序输出结果 for genre in ['Action', 'Comedy', 'History', 'Horror', 'Romance', 'Adventure']: print(f"{genre} : {len(genre_map[genre])}")
内容的提问来源于stack exchange,提问作者nimafanniasl
相关产品推荐
相关产品推荐

