如何将数值列表元素对应添加到字典列表的每个字典生成新列表?
解决方案
这里提供几种简单的实现方式,都是基于你提到的循环遍历思路:
方法1:按索引遍历修改
适合需要明确控制索引的场景,因为两个列表长度一致,可以通过索引一一对应:
# 你的原始数据 item_cart = [ {'Item #': 1, 'Price ': 3.99, 'Quantity': 10, 'Name': 'Porcupine'}, {'Item #': 2, 'Price ': 2.99, 'Quantity': 3, 'Name': 'Muffin2'} ] specific_item_total = [39.99, 8.97] receipt = [] # 遍历每个元素的索引 for i in range(len(item_cart)): # 复制原字典,避免修改原始的item_cart(如果不需要保留原数据,可以跳过copy) new_item = item_cart[i].copy() # 添加Total键值对 new_item["Total"] = specific_item_total[i] receipt.append(new_item) # 输出结果 print(*receipt, sep='\n')
方法2:用zip配对遍历(更易读)
用zip()把两个列表的对应元素打包,直接遍历每一组字典和总价,代码更直观:
item_cart = [ {'Item #': 1, 'Price ': 3.99, 'Quantity': 10, 'Name': 'Porcupine'}, {'Item #': 2, 'Price ': 2.99, 'Quantity': 3, 'Name': 'Muffin2'} ] specific_item_total = [39.99, 8.97] receipt = [] # 同时遍历字典和对应的总价 for item, total in zip(item_cart, specific_item_total): new_item = item.copy() new_item["Total"] = total receipt.append(new_item) print(*receipt, sep='\n')
方法3:列表推导式(简洁写法)
如果想一行搞定,可以用字典解包的方式生成新字典,适合追求代码简洁的场景:
item_cart = [ {'Item #': 1, 'Price ': 3.99, 'Quantity': 10, 'Name': 'Porcupine'}, {'Item #': 2, 'Price ': 2.99, 'Quantity': 3, 'Name': 'Muffin2'} ] specific_item_total = [39.99, 8.97] # 用列表推导式生成新列表,每个元素是添加了Total的新字典 receipt = [{**item, "Total": total} for item, total in zip(item_cart, specific_item_total)] print(*receipt, sep='\n')
注意:如果不需要保留原始的item_cart数据,也可以直接在原字典上修改,不用copy(),比如直接item["Total"] = total,这样item_cart本身也会被修改,根据你的需求选择即可。
内容的提问来源于stack exchange,提问作者py_coder1019
相关产品推荐
相关产品推荐

