【问题标题】:How to match input with elements in list/dictionary in Python3如何在Python3中将输入与列表/字典中的元素匹配
【发布时间】:2018-03-18 13:42:55
【问题描述】:

我对编码非常陌生,我正在尝试创建一个包含商品和价格的购物清单。 也就是说,一旦输入了所有项目,该函数应该计算总和并在您超出预算时停止。 所以我写了类似的东西:

def shoplist():
    list={"apple":30, "orange":20, "milk":60......}
    buy=str(input("What do you want to purchase?")
    If buy in list:
        While sum<=budget:
            sum=sum+??
shoplist ()

我真的不知道如何将商品的输入与列表中的价格匹配... 我的第一个想法是使用“if”,但是当列表中有超过 10 个项目和随机输入时,这有点不切实际。 我迫切需要帮助......所以任何建议都会很好! (或者如果你有更好的解决方案,并且认为我这样写完全是垃圾......请让我知道那些更好的解决方案是什么????????????

【问题讨论】:

    标签: python arrays input python-3.6


    【解决方案1】:

    您发布的代码不会在 python 中运行。 list 是一个内置函数,不应该用于变量名,并且由于它在这里引用一个 dict 对象而倍加混淆。 input() 已经返回一个 str 所以强制转换没有效果。 ifwhile 应该是小写的,并且没有缩进,所以我们无法知道这些语句的限制。

    错的太多了,看看这个:

    def shoplist(budget):
        prices = {"apple":30, "orange":20, "milk":60}
    
        # Initialise sum
        sum = 0
    
        while sum <= budget:
            buy = input("What do you want to purchase?")
    
            # Break out of the loop if the user hts <RETURN>
            if not buy: break
    
            if buy in prices:
                sum += prices[buy]   # This gets the price
            else:
                print("Invalid item", buy)
    
    shoplist(142)
    

    那么我改变了什么?预算必须来自某个地方,所以我将它作为参数传递(142,我编的)。我将总和初始化为零,并将while 循环移到外部。

    请注意大量的空格 - 它使代码更易于阅读并且对性能没有影响。

    需要进行大量改进。应该向用户显示可能的项目和价格的列表,以及每次购买还剩下多少预算。另请注意,可能会超出预算,因为我们的预算可能只有 30 个,但我们仍然可以购买牛奶(即 60 个) - 我们需要另一张支票(if 声明)那里!

    我会把改进留给你。玩得开心!

    【讨论】:

      【解决方案2】:

      以这个为例:

      # this is a dictionary not a list
      # be careful not using python reserved names as variable names
      groceries = {
          "apple":30, 
          "orange":20, 
          "milk":60
      }
      
      expenses = 0
      budget = 100
      cart = []
      # while statements, as well as if statements are in lower letter
      while expenses < budget:
          # input always returns str, no need to cast
          user_input = input("What do you want to purchase?")
          if user_input not in groceries.keys():
              print(f'{user_input} is not available!')
              continue
          if groceries[user_input] > budget - expenses:
              print('You do not have enough budget to buy this')
              user_input = input("Are you done shopping?Type 'y' if you are.")
              if user_input == 'y':
                  break
              continue
          cart.append(user_input)
          # this is how you add a number to anotherone
          expenses += groceries[user_input]
      print("Shopping cart full. You bought {} items and have {} left in your budget.".format(len(cart), budget-expenses))
      

      【讨论】:

        【解决方案3】:

        我已对您的代码进行了一些更改以使其正常工作,其中包括使用 # 符号指示的 cmets。

        最重要的两件事是所有括号都需要关闭:

        fun((x, y)  # broken
        fun((x, y)) # not broken
        

        并且Python中的关键字都是小写的:

        if, while, for, not # will work
        If, While, For, Not # won't work
        

        您可能对TrueFalse 感到困惑,它们可能应该是小写的。它们已经这样很久了,现在改变它们为时已晚。

        budget = 100 # You need to initialize variables before using them.
        
        def shoplist():
            prices = {         # I re-named the price list from list to prices
                'apple'  : 30, # because list is a reserved keyword. You should only
                'orange' : 20, # use the list keyword to initialize list objects.
                'milk'   : 60, # This type of object is called a dictionary.
            } # The dots .... would have caused an error.
            # In most programming languages, you need to close all braces ().
            # I've renamed buy to item to make it clearer what that variable represents.
            item = input('What do you want to purchase? ')
            # Also, you don't need to cast the value of input to str; 
            # it's already a str.
            if item in prices:
                # If you need an int, you do have to cast from string to int.
                count = int(input('How many? ')) 
                cost = count*prices[item] # Access dictionary items using [].
                if cost > budget:
                    print('You can\'t afford that many!')
                else:
                    # You can put data into strings using the % symbol like so:
                    print('That\'ll be %i.' % cost) # Here %i indicates an int.
            else:
                print('We don\'t have %s in stock.' % item) # Here %s means str.
        
        shoplist()
        

        许多初学者在 StackOverflow 上发布了损坏的代码,却没有说他们遇到错误或这些错误是什么。发布错误消息总是有帮助的。如果您还有其他问题,请告诉我。

        【讨论】:

          猜你喜欢
          • 2019-02-24
          • 1970-01-01
          • 1970-01-01
          • 2021-08-11
          • 1970-01-01
          • 2018-04-15
          • 1970-01-01
          • 2015-05-25
          • 2019-05-08
          相关资源
          最近更新 更多