繁体   English   中英

替代在python中编写15 if else语句

[英]Alternative to writing 15 if else statements in python

我想知道是否有更好的方法:我正在检查计算是否为0,如果为0,则什么也没有发生。 如果不是0,钱将被添加到玩家。 问题是我现在必须检查15种不同的股利计算,这将如何明智地执行? 我可以做15条if / else语句,但这很麻烦。 我的一个想法是使用下面的代码,但如果语句为true,则继续循环以检查其他语句,如果为true,则对它们进行操作。 这在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()

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]

这将为您提供一个布尔数组,可用于仅对所需股票建立索引

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM