如何在python中遍历字典的同时对特定键的值求和?

jljoyd4f  于 2022-12-27  发布在  Python
关注(0)|答案(3)|浏览(163)

创建一个解决方案,该解决方案接受一个整数输入,该整数输入标识要从Old Town Stock Exchange购买多少股股票,后跟表示股票选择的相等数量的字符串输入。下面的股票字典将可用的股票选择列为键,并将每次选择的成本列为值。

stocks = {'TSLA': 912.86 , 'BBBY': 24.84, 'AAPL': 174.26, 'SOFI': 6.92, 'KIRK': 8.72, 'AURA': 22.12, 'AMZN': 141.28, 'EMBK': 12.29, 'LVLU': 2.33}

Output the total cost of the purchased shares of stock to two decimal places.

The solution output should be in the format

Total price: $cost_of_stocks
Sample Input/Output:
If the input is

3
SOFI
AMZN
LVLU
then the expected output is

Total price: $150.53"

大家好,在zybooks上做一些练习作业,这一个一直难住我。

stocks = {'TSLA': 912.86, 'BBBY': 24.84, 'AAPL': 174.26, 'SOFI': 6.92,
          'KIRK': 8.72, 'AURA': 22.12, 'AMZN': 141.28, 'EMBK': 12.29, 'LVLU': 2.33}
selections = int(input())
i = 0
for i in range(selections):
    choices = (input())
    if choices in stocks:
        print((stocks[choices]))

这是目前我已经测试过的,它输出正确的值,无论我输入的键以及任何数量的键,我想输入

IE
input
3
TSLA
BBBY
AMZN

output
912.86
24.84
141.28

但是我不能使用sum(),因为它会给我一个类型错误,我该如何从用户那里得到一个特定数量的输入,把它赋给一个循环,使它只迭代用户指定的次数,然后输出与用户输入的键相关联的值的和呢?
谢谢你:)

rqdpfwrv

rqdpfwrv1#

您需要一个像res这样的变量来累加当前结果。
最好在循环外包含所选股票名称的input(),并将它们存储在适当的数据结构中,在本例中是一个数组。
此外,我假设input()是保证有效的,这是你提到的网站的真实情况。

stocks = {'TSLA': 912.86, 'BBBY': 24.84, 'AAPL': 174.26, 'SOFI': 6.92, 'KIRK': 8.72, 'AURA': 22.12, 'AMZN': 141.28,
          'EMBK': 12.29, 'LVLU': 2.33}

number_of_selection = int(input())
stock_selection = [input() for _ in range(number_of_selection)]

res = 0
for stock in stock_selection:
    res += stocks[stock]

print(f'Total price: ${res}')
kmpatx3s

kmpatx3s2#

你的代码没有把股票的价值加起来。你可以这样尝试:

stocks = {'TSLA': 912.86 , 'BBBY': 24.84, 'AAPL': 174.26, 'SOFI': 6.92, 'KIRK': 8.72, 'AURA': 22.12, 'AMZN': 141.28, 'EMBK': 12.29, 'LVLU': 2.33}

num_shares = int(input("Enter the number of shares you want to purchase: "))
total_price = 0

for i in range(num_shares):
  stock_name = input("Enter the name of the stock you want to purchase: ")

  if stock_name in stocks:
    total_price += stocks[stock_name]
  else:
    print("Invalid stock name")

print("Total price: $" + str(round(total_price, 2)))
mitkmikd

mitkmikd3#

stocks = {'TSLA': 912.86, 'BBBY': 24.84, 'AAPL': 174.26, 'SOFI': 6.92, 'KIRK': 8.72, 'AURA': 22.12, 'AMZN': 141.28, 'EMBK': 12.29, 'LVLU': 2.33}

# integer input identifying how many shares of stock are to be purchased
cost_of_stocks, to_purchase = 0, int( input() )

while to_purchase > 0:
  # stock name input
  stock_selection = str( input() )

  # default value if not exists
  cost_of_stocks += stocks.get( stock_selection, 0 )

  to_purchase -= 1

print( f"Total price: ${cost_of_stocks:.2f}" )

相关问题