我想知道是否有更好的方法来做到这一点:我正在检查一个计算值是否为0,如果为0则什么都没有发生。如果不是0,玩家将获得金钱。问题是,我现在必须检查15种不同的股息计算方法,这怎么做才是明智的呢?我可以做15个if/else语句,但那会很混乱。我的一个想法是使用下面的代码,但是如果语句为真,则继续循环,同时检查其他语句,如果为真,则对它们执行操作。这在Python中是可能的吗?你知道吗
我的另一个想法是做一个while循环,基本上每60秒,只要设置所有股票的除数,即使除数是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()
建立一个操作列表并存储要处理的值。如果您想知道是否有任何计算大于0,请使用函数
any()
如果您需要根据每个“函数”返回的值大于零来执行特定的计算,您可以将计算创建为函数,并创建一个字典,将结果作为值托管,函数名作为键(我们将计算的创建放在函数中,因为我们希望动态地获取值,而不是在字典已创建,因此我们每次都会根据传入的值创建一个新字典。这样你就知道哪一个返回什么值。如果要根据返回值大于0的内容进行处理,只需创建另一个字典并使用返回的键作为
to_do
字典的键:但是
if
语句没有什么错,读起来更干净。你知道吗不完全确定要执行什么操作,但能否将所有值放入numpy数组并检查:
这将给你一个布尔数组,你可以用它来索引你想要的股票
相关问题 更多 >
编程相关推荐