用python编写15条if-else语句的替代方法

2024-04-29 13:53:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否有更好的方法来做到这一点:我正在检查一个计算值是否为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()

Tags: importdefrandom语句googstockpriceaaplgetattr
2条回答

建立一个操作列表并存储要处理的值。如果您想知道是否有任何计算大于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语句没有什么错,读起来更干净。你知道吗

不完全确定要执行什么操作,但能否将所有值放入numpy数组并检查:

arr[arr==0]

这将给你一个布尔数组,你可以用它来索引你想要的股票

相关问题 更多 >