【问题标题】:how can i make function with list and dictionary become summary?如何使列表和字典的功能成为摘要?
【发布时间】:2020-06-05 15:19:16
【问题描述】:

我有数据样本:

bought = ['Banana','Banana','Pineapple','Pineapple']
price_of = {'Apple': 6, 'Avocado': 5, 'Banana': 3, 'Blackberries': 10, 'Blueberries':12, 'Cherries': 7, 'Pineapple': 7}
def summary(bought, price_of):
    for bought,n in price_of:
       multi = bought[keys] * price_of['keys']
       print(fruit_price[values],':', values)
       if total >= 10:
          print('discount', total * 5/10)

我仍然困惑于解决它,如果最低购买总额为 10,我想打折 5 我想这样输出:

2 Banana : 6
2 pineapple : 14
total : 20
discount price : #showing discount price

【问题讨论】:

  • 您的代码似乎没有尝试处理折扣价。
  • 开始清理这个代码片段: 1. bought 不应该同时是一个循环变量和一个函数输入,这至少是令人困惑的。 2. keysvalues 没有在任何地方定义。 3. 'keys' 不是price_of 中的键。 4. 一旦我们进入 for 循环,bought 是一个字符串,可能不应该被索引/不能被另一个字符串索引。 5. total 未定义。
  • 你能指导我一步一步解决吗?

标签: python list function dictionary transactions


【解决方案1】:
bought = ['Banana','Banana','Pineapple','Pineapple']
price_of = {'Apple': 6, 'Avocado': 5, 'Banana': 3, 'Blackberries': 10, 'Blueberries':12, 'Cherries': 7, 'Pineapple': 7}

def get_summary(items):
    result = {}
    for item in items:
        if not item in result:
            result[item] = {
                'count': 0,
                'price': 0
            }

        result[item]['price'] += price_of[item]
        result[item]['count'] += 1
    return result


def print_summary(items):
    total = 0
    for key in items:
        total += items[key]['price']
        print('{} {} {}'.format(items[key]['count'], key, items[key]['price']))
    print('Total: {}'.format(total))
    if total >= 10:
        print('Discount: {}'.format(total * 0.5))


print_summary(get_summary(bought))

# 2 Banana 6
# 2 Pineapple 14
# Total: 20
# Discount: 10.0

【讨论】:

    猜你喜欢
    • 2019-09-12
    • 2012-12-07
    • 2012-11-29
    • 2020-02-03
    • 2021-01-23
    • 1970-01-01
    • 2011-06-10
    • 1970-01-01
    • 2020-09-25
    相关资源
    最近更新 更多