使用字典python3中的列表计算收益

时间:2017-10-01 04:13:21

标签: python-3.x dictionary

stock_listings = {
            'GOOGL': [125, 772.88, 941.53],
            'MSFT' : [85, 56.60, 73.04],
             }

此字典的格式为 ' stock_name':[shares,purchase_price,current_price]

我需要通过使用字典中的数字计算收入并打印出收入..

收益=股票*(current_price - purchase_price)

您如何计算和打印收入?

非常感谢您的帮助!非常感谢你!

2 个答案:

答案 0 :(得分:0)

使用for循环

for stock in stock_listings:
    shares = stock_listings[stock][0]

等等

答案 1 :(得分:0)

您可以遍历stock_listings字典中的每个股票。一个简单的print()解决方案就像:

for each_stock in stock_listings.keys(): # iterates over each stock symbol in the stock_listings
  curr_stock_data = stock_listings[each_stock] # gets the current stock data from the listings
  curr_stock_earnings = (curr_stock_data[2]-curr_stock_data[1]) * curr_stock_data[0] # calculates this stock earnings with your formula
  print("The stock:", each_stock, ", earned: ", curr_stock_earnings) # outputs your result

这将提供如下输出:

The stock: MSFT , earned:  1397.4000000000003
The stock: GOOGL , earned:  21081.249999999996