You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中通过列表索引匹配获取对应时段水果价格并计算总价

水果价格计算功能实现

功能需求

输入水果名称、星期几和购买数量,执行以下操作:

  • 判断该水果是否在指定水果列表中,若存在则获取其索引
  • 根据输入的日期判断属于工作日还是周末,从对应的价格列表(工作日价格列表或周末价格列表)中取出相同索引位置的价格
  • 计算该价格与购买数量的乘积并输出
  • 若水果不在列表中或日期输入错误,则输出error

初始代码框架

fruits=["banana","apple","orange","grapefruit","kiwi","pineapple","grapes"]
weekdays=["Monday","Tuesday","Wednesday","Thursday","Friday"]
weekdays_price=[2.50,1.20,0.85,1.45,2.70,5.50,3.85]
weekend=["Saturday","Sunday"]
weekend_price=[2.70,1.25,0.90,1.60,3,5.60,4.20]

fruit=input()
day=input()
quantity=float(input())

if fruit in fruits:
    fruit_index=fruits.index(fruit)
    if day in weekdays:
        pass
        #taking the same index from weekdays_price and multiplying it's item value by the quantity
    elif day in weekend:
        pass
        #taking the same index from weekend_price and multiplying it's item value by the quantity
    else:
        print("error")
else:
    print("error")

完整实现代码

将框架中的pass替换为计算逻辑,并格式化输出结果(保留两位小数):

fruits=["banana","apple","orange","grapefruit","kiwi","pineapple","grapes"]
weekdays=["Monday","Tuesday","Wednesday","Thursday","Friday"]
weekdays_price=[2.50,1.20,0.85,1.45,2.70,5.50,3.85]
weekend=["Saturday","Sunday"]
weekend_price=[2.70,1.25,0.90,1.60,3,5.60,4.20]

fruit=input()
day=input()
quantity=float(input())

if fruit in fruits:
    fruit_index=fruits.index(fruit)
    if day in weekdays:
        total = weekdays_price[fruit_index] * quantity
        print("{0:.2f}".format(total))
    elif day in weekend:
        total = weekend_price[fruit_index] * quantity
        print("{0:.2f}".format(total))
    else:
        print("error")
else:
    print("error")

示例测试

输入:

apple
Monday
2

输出:2.40
(说明:apple在fruits中的索引为1,周一属于工作日,取weekdays_price索引1的1.20乘以2,得到2.40)

内容的提问来源于stack exchange,提问作者ddoch003

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 16:15:32