[英]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.