查找值之间的数字范围

时间:2017-11-09 01:37:51

标签: python-3.x

解决问题

我有一份股票价格清单,如下所示。我想提示用户投资的最低和最高股票价格。让我们说客户愿意将他们的钱投资于价值在50美元到100美元之间的股票。从下面的列表中,它应该在屏幕上打印出该范围之间的stock_price列表中的所有股票以及stock_symbol列表中的股票价格:符号。然后,用户可以从该列表中选择一个股票来投入资金。

# Stock lists for price and symbol
stock_price = [37.10, 80.07, 82.12, 93.27, 134.45, 131.05, 51.76, 114.63, 145.64, 77.99, 46.18]

stock_symbol = ['T', 'XOM', 'MDT', 'PG', 'JNJ', 'ECL', 'ABT', 'CVX', 'ITW', 'LOW', 'KO']

用户库存过滤器价格范围

stockRangeMin = (float(input("Enter the value for a minimum stock to purchase")

stockRangeMax = (float(input("Enter the value for a maximum stock to purchase")

我不知道该在这里输入什么来刺激上面用户指定的范围内的股票

要求用户购买库存符号,并从过滤后的清单中选择投资金额

stockChoice = (input("Enter the stock symbol you want to invest in")

investing = (float(input(f"Enter amount you'd like to invest in purchasing {stockChoice} today")

stockPurchased = investing/stockChoice

print ("Congrats, you have purchased {stockPurchased} shares of {stockChoice} with your investment amount of {investing}")

根据您的回复修改后的版本用于过滤掉指定价格范围内的符号

        stockRangeMin = (float(input("Enter the value for a minimum stock to purchase? $")))
        stockRangeMax = (float(input("Enter the value for a maximum stock to purchase? $")))
        analysis = [symbol for price, symbol in sorted(zip(stock_price, stock_symbol)) if stockRangeMin <= price <= stockRangeMax]
        print (f"\nThe Stock Symbols in your specified range of ${stockRangeMin} and ${stockRangeMax} are: \n",analysis)

这部分虽然我需要正确计算stockPurchased。不知道如何输入它。 analysis.price and analysis [price] and analysis [0]不起作用。

        stockChoice = (str(input("Enter the stock symbol you want to invest in")))
        stockPurchased = investing/analysis.price
        print ("Congrats, you have purchased {stockPurchased} shares of {stockChoice} with your investment amount of {investing}")
        break

1 个答案:

答案 0 :(得分:1)

这是一个列表理解,通过压缩列表并检查价格

[symbol for price, symbol in zip(stock_price, stock_symbol) if stockRangeMin <= price <= stockRangeMax]