如何访问嵌套列表中指定商品的价格并进行数值运算?
访问嵌套列表中商品的名称和价格
直接索引访问
你的嵌套列表里每个元素都是包含「商品名+价格」的子列表,直接用索引就能快速访问:
- 获取Chicken的名称:
ShoppingList[0][0],返回值为"Chicken" - 获取Chicken的价格:
ShoppingList[0][1],返回值为10
如果要拿Chicken的价格和另一个数值做减法,代码示例如下:
ShoppingList = [["Chicken", 10], ["Water", 5], ["Detergent", 8]] # 假设要减去的数值是3 result = ShoppingList[0][1] - 3 print(result) # 输出7
遍历查找(适合商品位置不固定的场景)
如果不确定目标商品在列表中的位置,可以通过遍历列表来定位:
ShoppingList = [["Chicken", 10], ["Water", 5], ["Detergent", 8]] target_name = "Chicken" target_price = None # 遍历列表匹配目标商品 for item_name, price in ShoppingList: if item_name == target_name: target_price = price break # 找到价格后执行减法操作 if target_price is not None: subtract_result = target_price - 2 print(subtract_result) # 输出8
内容的提问来源于stack exchange,提问作者Will
相关产品推荐
相关产品推荐

