如何从字典中获取值,计算后返回最大值的键
到目前为止,我的作业还算简单。我在用Python 3。
GetSale - 这个函数的作用是找出卖出股票的最大预期价值。股票的预期销售价值是当前利润减去未来股票的价值: 预期销售价值 = ( ( 当前价格 - 买入价格 ) - 风险 * 当前价格 ) * 股票数量 GetSale函数应该计算投资组合中每只股票的这个值,并返回预期销售价值最高的股票符号。
我们使用了三个独立的字典:Names(名字)、Prices(价格)和Exposure(风险暴露)。
在GetSale函数中,我知道需要调用Prices和Exposure字典来获取公式中的值;但是,我不知道怎么获取这些值并进行计算。
到目前为止,这就是我的代码:
Names = {}
Prices = {}
Exposure = {}
def AddName():
name = input('Please enter the company name: ')
stock_symbol = input('Please enter the comapny stock symbol: ')
Names[name] = stock_symbol
def AddPrices():
stock_symbol = input('Please enter the company stock symbol: ')
Buy_Price = float(input('Please enter the buy price: '))
Current_Price = float(input('Please enter the current price: '))
Prices[stock_symbol] = 'Buy_Price:', [Buy_Price], 'Current Price', [Current_Price]
def AddExposure():
stock_symbol = input('Please enter the company stock symbol: ')
Risk = float(input('Please enter the risk of the stock: '))
Shares = float(input('Please enter the shares of the stock: '))
Exposure[stock_symbol] = 'Risk:', [Risk], 'Shares:', [Shares]
def AddStock():
AddName()
AddPrices()
AddExposure()
我知道这肯定需要用到循环,因为需要反复运行这个公式来找出最大的预期销售价值,然后返回那个最大的股票符号。
def GetSale():
for stock_symbol, Buy_Price, Current_Price in Prices.items():
附言:如果我说得不够清楚和具体,我很抱歉,我尽量简明扼要,请原谅,这是我第二次发帖。
3 个回答
在编程中,有时候我们会遇到一些问题,特别是在使用某些工具或库的时候。这些问题可能会让我们感到困惑,尤其是当我们刚开始学习编程的时候。比如,有人可能会在使用某个函数时,发现它的表现和预期不一样。这种情况很常见,尤其是在处理数据或调用外部资源时。
解决这些问题的第一步是仔细阅读文档,了解这个函数的具体用法和限制。很多时候,文档中会有示例代码,帮助我们理解如何正确使用这些工具。
另外,查看其他开发者的经验也是一个好办法。像StackOverflow这样的社区,聚集了很多有经验的程序员,他们分享了自己的问题和解决方案。通过阅读这些内容,我们可以获得灵感,找到解决自己问题的方法。
总之,遇到问题时,不要着急,先查阅资料,看看别人是怎么解决的,慢慢积累经验,你会越来越熟练的。
def addName(names):
names[input("Enter company name: ")] = input("Enter Stock Symbol: ")
def addPrices(prices):
symbol = input("Enter stock symbol: ")
prices[symbol] = {}
prices[symbol]['buy'] = input("Enter buy price: ")
prices[symbol]['current'] = input("Enter current price: ")
def addExposure(exposure):
symbol = input("Enter stock symbol: ")
exposure[symbol] = {}
exposure[symbol]['risk'] = input("Enter stock risk: ")
exposure[symbol]['shares'] = input("Enter stock shares: ")
def getSale(names, prices, exposure):
return names[max(names, key=lambda name: ((prices[names[name]]['current'] - prices[names[name]]['buy']) - exposure[names[name]]['risk']*prices[names[name]]['current']) * exposure[names[name]]['shares'])]
所以,你想把一些数值代入一个公式,然后找出最大的那个键值?这里有一个程序:
# I'm just going to name your dictionary myDict
for i in myDict:
myDict[i] = whatever_your_equation_is(myDict[i])
return myDict.keys[myDict.values().index(max(myDict.values()))]
如果这个没有回答到你的问题,我很抱歉。这是你的第二个问题,而这是我的第三个回答!
我怎么从字典里获取值呢?
d.values()
把它们放进一个公式里算一算
(equation(value) for value in d.values())
然后找出值最大的那个键
这时候事情就有趣了。你需要同时获取键和值。那我们重新来过。
我怎么从字典里获取键和值呢?
d.items()
把这些值放进一个公式里算一算
((equation(v), k) for k, v in d.items())
然后找出值最大的那个键
max((equation(v), k) for k, v in d.items())
不对,是键,不是值和键一起
max((equation(v), k) for k, v in d.items())[1]