【问题标题】:How to make looping 3 dimensions like that?如何制作这样的循环 3 维?
【发布时间】:2020-09-24 16:32:31
【问题描述】:

我尝试用这样的代码制作一个迷你交易摘要:

price = {'mouse':10, 'hdd':60, 'rmd':23}
buying = {'mouse':3, 'hdd':2}

def total(price,buying):
    print(sum(multiple = price.values() * buying.values()))

输出:

3 mouse : 30
2 hdd : 120 

【问题讨论】:

  • 您能否详细说明您的问题或您想要达到的目标?
  • 这不是三个维度。您使用 2 个字典,每个“1 维”(未嵌套)

标签: python function loops dictionary


【解决方案1】:

你在寻找这样的东西吗?

def total(price, buying):
    for item, n in buying.items():
        print(n, item, ':', n * price[item])

【讨论】:

    【解决方案2】:

    您可以从price 中选择一个元素,然后从buying 中找到它的值并打印出来。

    price = {'mouse':10, 'hdd':60, 'rmd':23}
    buying = {'mouse':3, 'hdd':2}
    def total(price,buying):
        for item in price.keys():
            #this will default to 0 if no item of this type is not sold.
            quantity = buying.get(item, 0)
            mult = price[item] * quantity
            print("{} {}: {}".format(quantity, item, mult))
    

    输出:

    2 hdd: 120
    3 mouse: 30
    0 rmd: 0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-03
      • 2019-04-01
      • 2017-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-27
      相关资源
      最近更新 更多