Python遍历字典集合重复输出修复及结果存储咨询
错误原因
你原代码的问题在于循环逻辑冗余:duck_collection共有3个元素,for循环会执行3次,你在每次循环内部都重复计算、打印了3个账号的差值,最终得到3*3=9行输出,且全程没有用到遍历得到的循环变量duck。
修改后代码
duck_1 = { "first_name": "Davey", "followers": 12865, "following": 120, "weapons": ["wit", "steely stare", "devilish good looks"] } duck_2 = { "first_name": "Jim", "followers": 123, "following": 5000, "weapons": ["squeak"] } duck_3 = { "first_name": "Celest", "followers": 40189, "following": 1, "weapons": ["politics", "dance moves", "chess grandmaster", "immortality"] } duck_collection = [ duck_1, duck_2, duck_3 ] # 初始化存储差值的列表(Python变量名不支持空格,因此调整为驼峰命名) TrendyDucks = [] for duck in duck_collection: # 计算当前遍历账号的差值 diff = duck['followers'] - duck['following'] print(diff) TrendyDucks.append(diff)
运行效果
- 打印输出共3行,完全符合要求:
12745 -4877 40188
- 最终
TrendyDucks列表的值为[12745, -4877, 40188],满足存储需求。
内容的提问来源于stack exchange,提问作者kamran khan
相关产品推荐
相关产品推荐

