首页 > 解决方案 > 在这种情况下如何从二维数组中调用元素?

问题描述

data = [['01','Book',5],['02','Pen',2],['03','Pencil',1.5],['04','Paper',15],['05','USB Drive',20]]

提示用户输入产品名称和数量。根据他/她的需要重复多次。计算并显示用户输入的产品的数量、名称和价格。计算并显示购买这些产品的总成本。

more = 'yes'
shopping_list = []
while more == 'yes':
    user_input = input('Enter a product:')
    user_quantity = int(input('Enter the number of products:'))
    shopping_list.append(user_input)
    shopping_list.append(user_quantity)
    more = input('Would you like more?')

我的代码不起作用..

标签: python

解决方案


我会格式化数据以将其保存在字典中,唯一键是产品名称,值是价格

formatted_data={j:k for i,j,k in data}

格式化的数据如下所示:

{'书':5,'纸':15,'笔':2,'铅笔':1.5,'USB驱动器':20}

more = 'yes'
shopping_list = []
while more == 'yes':
    user_input = input('Enter a product:')
    user_quantity = int(input('Enter the number of products:'))
    if user_input in formatted_data:
        get_price_of_product=formatted_data[user_input]
        get_quantity=user_quantity
        amount=get_price_of_product * get_quantity
        shopping_list.append((user_input,amount))
    else:
        print('Enter valid product name')
    more = input('Would you like more?')

推荐阅读