python - 将字典中的一些值相乘
问题描述
我正在编写一个程序,允许用户从菜单中选择选项,并在此基础上打印所选选项的详细信息。我需要将数量和价格相乘才能得到成本。问题是,我的价格和数量在嵌套字典中。如果用户选择选项 1> 3AB,它应该根据 3AB 的数量和价格打印出成本。我怎么做?
stock = {
'3AB': {'Name': 'Telcom', 'Purchase Date': '12/12/2018', 'Price': '1.55', 'Volume':'3000'},
'S12': {'Name': 'S&P', 'Purchase Date': '12/08/2018', 'Price': '3.25', 'Volume': '2000'},
'AE1': {'Name': 'A ENG', 'Purchase Date': '04/03/2018', 'Price': '1.45', 'Volume': '5000'}
}
def menu():
menuChoice =True
while menuChoice:
print ("""
Menu
1. List Holding and Sold details for a Stock
2. Buy Stock
3. Sell Stock
4. list Holdings
5. list Sold Stock
0. Exit
""")
menuChoice= input("Enter Choice: ")
if menuChoice=="1":
option1()
elif menuChoice=="2":
print("\n Buy Stock")
elif menuChoice=="3":
print("\n Sell Stock")
elif menuChoice=="4":
print("\n List Holdings")
elif menuChoice=="5":
print("\n List Sold Stock")
elif menuChoice=="0":
break
elif menuChoice !="":
print("\n Invalid. Please Re-enter choice: ")
def option1():
input1 = input("Please enter code: ").lower()
test = stock['3AB']['Volume'] * stock['3AB']['Price']
print(test)
if input1.upper() == "3AB":
print("\nCode: " + input1.upper())
print("Name: " + stock['3AB']['Name'])
print("Last Purchase Date: " + stock['3AB']['Purchase Date'])
print("Average Price: " + stock['3AB']['Price'])
print("Volume: " + stock['3AB']['Volume'])
print("Investment Cost ($): " + ())
elif input1.upper() == "S12":
print("\nCode: " + input1.upper())
print("Name: " + stock['S12']['Name'])
print("Last Purchase Date: " + stock['S12']['Purchase Date'])
print("Average Price: " + stock['S12']['Price'])
print("Volume: " + stock['S12']['Volume'])
elif input1.upper() == "AE1":
print("\nCode: " + input1.upper())
print("Name: " + stock['AE1']['Name'])
print("Last Purchase Date: " + stock['AE1']['Purchase Date'])
print("Average Price: " + stock['AE1']['Price'])
print("Volume: " + stock['AE1']['Volume'])
else:
print("Stock is not found in your portfolio.")
print(input("Enter another option: "))
menu()
解决方案
问题是您将值作为字符串存储在原始字典中。要解决它,您可以将值转换为浮点数:
test = float(stock['3AB']['Volume']) * float(stock['3AB']['Price'])
或者不要更改代码并将值存储为数字:
stock = {
'3AB': {'Name': 'Telcom', 'Purchase Date': '12/12/2018', 'Price': 1.55, 'Volume':3000},
'S12': {'Name': 'S&P', 'Purchase Date': '12/08/2018', 'Price': 3.25, 'Volume': 2000},
'AE1': {'Name': 'A ENG', 'Purchase Date': '04/03/2018', 'Price': 1.45, 'Volume': 5000}
}
顺便说一句,您的代码在下一行中仍然存在一个问题。您必须定义要打印的值:
print("Investment Cost ($): " + ())
推荐阅读
- r - 无法在 macos 上安装软件包
- javascript - 将复选框更改为选中单击跨度不起作用
- angular - 对带有 ionic 4 的路由器的说明
- dart - 获取 _InternalLinkedHashMap
' 不是类型 'FutureOr 的子类型 ' - java - 在 Spring Boot 中将实体与有效负载 (dto) 混合 - 最佳实践
- sql-server - 创建一个包含连接信息的配置文件,然后引用该连接
- php - codeigniter 从 insert_batch 的字符串修改数组
- c - 如何在 Raspberry PI 3 上的 C++ 中达到超时后清除 select() 状态
- java - Play Framework For Scala:[类型 BooksController 不是包控制器的成员]
- javascript - mxGraph 库是否适合绘制如下图这样的复杂电气图?