1

私はテキストベースの冒険に取り組んでおり、ランダム関数を実行したいと考えています。すべてのアドベンチャー機能は、「adv」の後に 3 桁の数字が続きます。
go() を実行すると、次のように返されます。

IndexError: Cannot choose from an empty sequence

これは、allAdv がまだ空であるためです。シェルで go() を1行ずつ実行すると機能しますが、関数では機能しません。私は何を取りこぼしたか?

import fight
import char
import zoo
import random

#runs a random adventure
def go():
    allAdv=[]
    for e in list(locals().keys()):
        if e[:3]=="adv":
            allAdv.append(e)
    print(allAdv)
    locals()[random.choice(allAdv)]()


#rat attacks out of the sewer
def adv001():
    print("All of a sudden an angry rat jumps out of the sewer right beneath your feet. The small, stinky animal aggressivly flashes his teeth.")
    fight.report(zoo.rat)
4

1 に答える 1

0

これは主にスコープの問題によるもので、 locals()inを呼び出すと、この関数で定義されgo()たローカル変数のみが出力されます。allDev

locals().keys()  # ['allDev']

ただし、シェルで次の行ごとに入力する場合は、この場合は同じレベルにあるため、locals()含めてください。adv001

def adv001():
    print("All of a sudden an angry rat jumps out of the sewer right beneath your feet. The small, stinky animal aggressivly flashes his teeth.")
    fight.report(zoo.rat)

allAdv=[]
print locals().keys()  #  ['adv001', '__builtins__', 'random', '__package__', '__name__', '__doc__']
for e in list(locals().keys()):
    if e[:3]=="adv":
        allAdv.append(e)
print(allAdv)
locals()[random.choice(allAdv)]()

でこれらの関数変数を本当に取得したい場合は、次のように変更することをgo()検討してください。locals().keys()globals().keys()

于 2015-02-13T13:13:03.183 に答える