2017-10-05 60 views
0

比如我有我該如何去通過一個輸入變量數組,並讀取輸出變量

commandz=[["yes","no"],["hi","hi"]] 
async def handle_command(message): 
    print('Noticed: ' + message.content) 
    if message.content == 'tokenreset'+str(key): 
     await client.send_message(message.channel, 'code accepted') 
    i = 0 
    for i in commandz[i][0]: 
     comm = commandz[i][0] 
     if comm == message.content: 
      await client.send_message(message.channel, commandz[i][1]) 

該錯誤消息我得到的是

C:\Users\trisimix>python "c:\Users\trisimix\compsocbot\main.py" 
Found saved token in stored.py, use phrase tokenreset1424629785956179 to undo this. 
Logged in as[198866998225141760]NOTAKOALAONACOMPUTERINVENEZUELA 
-------- 
Noticed: hi 
Ignoring exception in on_message 
Traceback (most recent call last): 
    File "C:\Users\trisimix\AppData\Local\Programs\Python\Python36\lib\site-packages\discord\client.py", line 307, in _run_event 
    yield from getattr(self, event)(*args, **kwargs) 
    File "c:\Users\trisimix\compsocbot\main.py", line 34, in on_message 
    await handle_command(message) 
    File "c:\Users\trisimix\compsocbot\main.py", line 42, in handle_command 
    comm = commandz[i] 
TypeError: tuple indices must be integers or slices, not str 

我試圖讓我的程序使用if語句檢查數組中的每個命令,然後使用輸出進行響應。

+0

'commandz [i] [0]'是字符串'「是」',所以你在循環「y」,「e」和「s」。你嘗試訪問'for循環的第一行'commandz ['y'] [0]' –

+0

我試圖匹配一個字符串與字符串yes和hi,並且返回no或hi如果它的匹配 – trisimix

回答

0

從代碼中的第6行起(即for循環):

for comm in commandz: 
    if comm[0] == message.content: 
     await client.send_message(message.channel, comm[1]) 

與您的代碼的問題是,你遍歷字符串的字符(commandz[0][0]),當你真正想要的是循環遍歷您的嵌套列表的列表(即["yes","no"]["hi","hi"],這簡直是在commandz

請注意,我用的是變量comm在作爲列表中的commandz,而不是這些列表中的第一個索引,即yeshi我認爲你打算使用它作爲