我想知道是否有更好的方法来做这件事:我正在检查一个计算是否为0,如果为0,则什么都不发生。如果没有,则将0钱添加到玩家。问题是,我现在必须检查15种不同的股息计算方式,这样做是明智的吗?我可以做15个if/else语句,但那会很混乱。我的一个想法是使用下面的代码,但如果语句为真,则继续循环以检查其他语句,如果为真,则对它们执行操作。这在Python中是可能的吗?
我的另一个想法是做一个while循环,基本上每隔60秒,就为所有的股票设置dividen,即使dividens为0,但我认为如果玩家在执行过程中做了其他事情,这有可能成为bug。一些示例代码:
import random
import sys
import time
import os
def playerStatus():
playerStatus.playerMoney = 10000
playerStatus.playerLoan = 0
def dividends():
while True:
networthCalc()
pm = playerStatus.playerMoney
print("cash:", pm)
dividends.aapl = networthCalc.aapl / random.randint (20,30)
dividends.goog = networthCalc.goog / random.randint (20,30)
time.sleep(1)
if dividends.aapl > 0:
newCash = dividends.aapl + pm
setattr(playerStatus, "playerMoney", newCash)
print("aapl payed div:", dividends.aapl)
elif dividends.goog > 0:
newCash = dividends.goog + pm
setattr(playerStatus, "playerMoney", newCash)
print("goog payed div:", dividends.goog)
else:
pass
def networthCalc():
networthCalc.aapl = getattr(stockPrice, "aapl") * getattr(showAssets, "aapl")
networthCalc.goog = getattr(stockPrice, "goog") * getattr(showAssets, "goog")
def showAssets():
showAssets.aapl = 10
showAssets.goog = 10
def stockPrice():
stockPrice.aapl = 200
stockPrice.goog = 200
playerStatus()
showAssets()
stockPrice()
networthCalc()
dividends()
发布于 2018-08-22 04:04:55
构建一个操作列表并存储它的值以进行处理。如果您想知道是否有任何计算大于0,请使用函数any()
x = 3
calculations = [x+1,x+2,x+(-3)]
if any(calculations):
#do something
print("there's something above 0")
如果您需要根据每个“函数”返回大于零的值进行特定的计算,您可以将计算创建为函数,并创建一个字典来将结果作为值托管,并将函数名作为键(我们将计算的创建放在一个函数中,因为我们希望动态获取值,而不是在字典创建的时候,因此我们每次都会根据传入的值创建一个新的值)。这样你就知道哪一个返回了什么值。如果您希望根据返回大于0的内容进行处理,只需创建另一个字典,并使用返回的键作为to_do
字典的键:
def aapl_calc(value):
return value + 5
def goo_calc(value):
return value -2
def calculate_everything(x):
return {"aapl":aapl_calc(x), "goo":goo_calc(x)}
def appl_to_do():
print("appl was greater than zero")
def goo_to_do():
print("goo was greater than zero")
to_do = {"aapl": appl_to_do, "goo":goo_to_do}
results = calculate_everything(2)
#checking if anything is greater than zero is easy
if any(results.values()):
print("something return as 0")
#creating a list of greater than 0 to use as keys
greater_than_zero = [key for key, val in results.items() if val]
#run each of the values greater than 0
for each in greater_than_zero:
to_do[each]()
但是if
语句没有什么问题,读起来会更干净。
https://stackoverflow.com/questions/51955624
复制相似问题