Попытка умножить количество каждого предмета на цену, а затем найти общую среднюю цену всех купленных предметов.

shopping_cart = {
    "tax": .08,
    "items": [
        {
            "title": "orange juice",
            "price": 3.99,
            "quantity": 1
        },
        {
            "title": "rice",
            "price": 1.99,
            "quantity": 3
        },
        {
            "title": "beans",
            "price": 0.99,
            "quantity": 3
        },
        {
            "title": "chili sauce",
            "price": 2.99,
            "quantity": 1
        },
        {
            "title": "chocolate",
            "price": 0.75,
            "quantity": 9
        }
    ]
}


total = sum(val[-1] * sum[-2] for val in shopping_cart.values())

print(total)

Ошибка состояний с плавающей точкой не является подпиской.

0
Jeff R 16 Авг 2019 в 18:31

2 ответа

Лучший ответ

Как то, что сказал Скаймон, но он усредняет по всем пунктам в диктанте, а не использует «количество». Попробуйте что-нибудь подобное?

total_price = sum([item['price'] * item['quantity'] for item in shopping_cart['items']])
total_items = sum([item['quantity'] for item in shopping_cart['items']])
average_price_per_item = total_price/total_items

Чтобы сделать это более эффективно, вы можете повторить корзину только один раз.

cost = 0
quantity = 0

for item in shopping_cart['items']:
    cost += item['price'] * item['quantity']
    quantity += item['quantity']

average_cost = cost/quantity
1
Seb Clarke 16 Авг 2019 в 15:55

Вам нужно получить доступ к каждому элементу в dict, чтобы вы могли сделать это так:

shopping_cart = { "tax": .08, "items": [ { "title": "orange juice", "price": 3.99, "quantity": 1 }, { "title": "rice", "price": 1.99, "quantity": 3 }, { "title": "beans", "price": 0.99, "quantity": 3 }, { "title": "chili sauce", "price": 2.99, "quantity": 1 }, { "title": "chocolate", "price": 0.75, "quantity": 9 } ] }

total = sum(item.get("price") * item.get("quantity") for item in shopping_cart.get("items"))
average = total / len(shopping_cart.get("items"))

print(total)
print(average)

Это приводит к:

22,67

4,534

0
skymon 16 Авг 2019 в 15:41