Python列表内字典操作:统计黄瓜总销量及过滤weekday字段打印咨询
代码修改优化方案
现存代码问题
- 函数名使用了Python内置关键字
list,会覆盖原生列表类型,属于命名冲突 - 循环逻辑错误:每次遍历都调用
next查找匹配的黄瓜条目,只会重复返回第一个符合条件的黄瓜数据,既没有实现求和,也没有过滤字段的功能
需求1:计算黄瓜总销量
直接用生成器表达式遍历列表累加重量即可,代码简洁高效:
def calc_cucumber_total(listing): return sum(item['mass'] for item in listing if item['name'] == 'cucumber')
你提供的样例数据运行后返回结果为100,也就是总销量100千克。
需求2:打印字典时排除weekday字段
用字典推导式过滤掉key为weekday的键值对即可:
def print_without_weekday(listing): for item in listing: filtered_item = {key: value for key, value in item.items() if key != 'weekday'} print(filtered_item)
完整可运行代码
listing = [ {'mass': 20, 'name': 'onion', 'weekday': 'monday'}, {'mass': 10, 'name': 'garlic', 'weekday': 'tuesday'}, {'mass': 40, 'name': 'carrot', 'weekday': 'monday'}, {'mass': 90, 'name': 'cucumber', 'weekday': 'saturday'}, {'mass': 80, 'name': 'onion', 'weekday': 'sunday'}, {'mass': 30, 'name': 'parslay', 'weekday': 'sunday'}, {'mass': 20, 'name': 'onion', 'weekday': 'sunday'}, {'mass': 10, 'name': 'cucumber', 'weekday': 'wednesday'}, {'mass': 1, 'name': 'garlic', 'weekday': 'sunday'}, ] # 计算黄瓜总销量 def calc_cucumber_total(listing): return sum(item['mass'] for item in listing if item['name'] == 'cucumber') # 打印排除weekday的所有条目 def print_without_weekday(listing): for item in listing: print({k:v for k,v in item.items() if k != 'weekday'}) # 测试调用 print("黄瓜总销量:", calc_cucumber_total(listing)) print("\n排除weekday字段的所有条目:") print_without_weekday(listing)
内容的提问来源于stack exchange,提问作者Learningmachine
相关产品推荐
相关产品推荐

