python - 在这种情况下如何从二维数组中调用元素?
问题描述
data = [['01','Book',5],['02','Pen',2],['03','Pencil',1.5],['04','Paper',15],['05','USB Drive',20]]
- 每个二级列表中的第一个元素是产品 ID
- 第二个元素是产品名称
- 第三个要素是产品价格。
提示用户输入产品名称和数量。根据他/她的需要重复多次。计算并显示用户输入的产品的数量、名称和价格。计算并显示购买这些产品的总成本。
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?')
我的代码不起作用..
解决方案
我会格式化数据以将其保存在字典中,唯一键是产品名称,值是价格
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?')
推荐阅读
- cocoapods - pod install 和 pod install --repo-update 有什么区别?
- php - WordPress 主题如何将 HTML 代码添加到管理页面
- excel - VBA从一张纸上获取信息并将其复制到另一张纸上
- typescript - 在 TypeScript 中将函数签名设置为自定义类型
- javascript - 滚动时标题抖动/颤抖 - jQuery 滚动问题
- java - 解密结果 128-aes-CBC 在 C 和 Java Cipher 中的 mbedtls 之间的差异
- mysql - SQL MySQL IN 运算符与表达式不是列
- r - 如何输出多维数组
- app-store - 在 iTunes Connect 中为 iAP 添加新的本地化(语言)是否需要(重新)批准 IAP?
- javascript - 如何在非模块脚本中注入 Webpack DefinePlugin 变量