簡體   English   中英

返回一個<class 'type'>使用 random.choices()

[英]returning a <class 'type'> using random.choices()

我們目前正在為學校編寫一個小游戲,為了選擇哪些道具會產生,我們使用choices()方法來獲得加權概率並從包含類名的列表中進行選擇。 我面臨的問題是,由於choices()方法返回一個數組,我似乎無法將我的對象附加到列表中,這是代碼,如果您有時間幫助我們...謝謝

def Choice2():
    Type2 = choices([Healboost, DmgsUp, FireRateBoost, ""],weights=proba_powerups) #[0][1][2] are my class names, [3] is for no powerup
    CreatePowerUps(str(Type2)) # converting to str in order to strip "[]"


def CreatePowerUps(a):
    global Time,powerups
    a = a.strip("[]") # removing the "[]"
    print(f"a : {type(a)}") # prints "a : <class 'str'>"
    if Time > 0:
        if a == Healboost :
            powerups.append(a())
        elif a == FireRateBoost :
            powerups.append(a())
        elif a == DmgsUp :
            powerups.append(a())
        elif a == "":
            pass
        if Time > 1200:
            Time -= 10
        print(powerups) # debugging purpose (list stays empty)
        NFP.after(Time,Choice2)
    else:
        pass

你到底為什么要將列表轉換為字符串? 您只需要選擇第一個元素。

這是一個簡化的示例:

from random import choices

x, y, z = [0, 1, 2]
powerups = []

def choice2():
    type2 = choices([x, y, z, ""], weights=[1] * 4)
    create_power_ups(type2[0])

def create_power_ups(a):
    if a in (x, y, z):
        powerups.append(a)
    print(powerups)

choice2()

運行幾次,您將看到所有不同的選項: [][0][1][2]

順便說一句,UpperCamelCase 應該保留給類名,所以我在那里修復了它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM