【问题标题】:How to extract corresponding value from python dictionary?如何从python字典中提取相应的值?
【发布时间】:2023-03-17 13:49:01
【问题描述】:

我写了简单的python,它给出了系统如何执行的想法,但没有计算总数。现在我想要的是获得相应的值(即锥形类型、每个勺的勺子风味和每个浇头的顶部风味)并计算总成本,最后显示详细选择的项目(项目-->价格和数量)和总和。

customername = input("Enter the customer's name....")
ic_no = int(input("Enter the number of ice-creams you want to buy"))
total = {}
for i in range(1, ic_no + 1):
    print("For item ", i)
    cone = int(input("Enter the cone type: "))
    scoop = int(input("Enter the scoop amount: "))
    for j in range(1, scoop+1):
        #select flavor type for each scoop
        flavor = int(input("Entr No."+ str(j) +" flavor")) 
    topping = int(input("Entr the toppings amount: "))
    for k in range(1, topping+1):
        #select flavor type for each topping
        top_flavor = int(input("Entr No." + str(k) +" topping flavor"))

print("Total price is ", total)

我想简单地通过传递数字来获取选定的项目。例如:1 表示“普通”圆锥类型。

cone_type = (
    {"name": "Plain",     "price": 2},
    {"name": "Wafle",     "price": 3},
)
scoop_flavor = (
    {"name": "Mint",        "price": 1},
    {"name": "Caramel",     "price": 1},
    {"name": "Chocolate",   "price": 1},
    {"name": "Apple",       "price": 1},
)

topping_flavor = (
    {"name": "Chocolate",         "price": 1},
    {"name": "Caramel",           "price": 0.5},
    {"name": "Peanut",            "price": 0.5},
    {"name": "Coconut Sprinkle",  "price": 0.25},
)

【问题讨论】:

    标签: python dictionary sharp


    【解决方案1】:

    我想添加到 blue_note 答案,并建议使用 Enum 来获取如下的 cone_type:

      class ConeType (enum.Enum):
            PLAIN = 1
            WAFLE = 2
    
    print(ConeType(1).name);
    

    【讨论】:

      【解决方案2】:

      只需过滤元组以获取(唯一)有效条目,并获取其价格

      def get_price(cone_types, cone_name):
          return [cone['price'] for cone in cone_types if cone['name']==cone_name][0]
      

      但是,如果您只有名称和价格,最好直接将您的字典形成为

       cone_types {'plain': 2, 'wafle': 3}
      

      对于其他字典也是如此。这就是字典的用途,键应该具有区分价值。

      【讨论】:

        【解决方案3】:

        您可以将库存数据结构更改为 int:list-of-details 的字典,而不是当前的字典列表。

        例如:

        cone_type = {1:["Plain", 2], 2:["Waffle", 3]}
        

        对于普通锥体,使用cone_type[1][0] 访问名称,使用cone_type[1][1] 访问价格。

        您还可以考虑为蛋筒、口味和配料创建一个类。然后,您可以将它们用作字典的值,而不是列表。这样做可以让您以cone_type[1].getName()cone_type[1].getPrice() 的身份访问产品信息,这样更容易阅读!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-10-23
          • 1970-01-01
          • 2016-11-26
          • 2022-11-22
          • 2022-01-11
          • 2022-01-25
          • 2021-09-03
          相关资源
          最近更新 更多