簡體   English   中英

Python:通過用戶輸入從字典中調用函數

[英]Python: Calling a function from a dictionary via user input

我正在嘗試使用字典鍵調用函數。 目前,詞典中只有一個功能,但我打算添加更多功能。 下面的代碼用於顯示列表,因為函數“ loadlist”沒有參數,並且在將文件打開為f時,我已將“ gameone.txt”寫入主體代碼中。

我想將文件名作為loadlist函數的參數,以便用戶輸入例如... loadlist('gameone.txt')或loadlist('gametwo.txt')等,具體取決於他們想要顯示的內容。

def interact():

command = raw_input('Command:')

def loadlist():

    with open('gameone.txt', 'r') as f:
        for line in f:
            print line


dict = {'loadlist': loadlist}
dict.get(command)()

return interact()

相互作用()

我已經嘗試過下面的代碼,但無法解決問題。

def interact():

command = raw_input('Command:')

def loadlist(list):

    with open(list, 'r') as f:
        for line in f:
            print line


dict = {'loadlist': loadlist}
dict.get(command)()

return interact()

相互作用()

感謝您的任何投入。

您可以嘗試使用* args。

def interact():

    command,file_to_load = raw_input('Command:').split(' ')

    # *args means take the parameters passed in and put them in a list called args
    def loadlist(*args):

        # get the argument from args list
        filename = args[0]

        with open(filename, 'r') as f:
            for line in f:
                print line


    dict = {'loadlist': loadlist}
    dict.get(command)(file_to_load)

interact()

暫無
暫無

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

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