2016-05-15 138 views
0

我想通過python中的三重嵌套列表進行搜索。我想出了一種超級混亂的方式,不起作用。你如何有效地做到這一點?我正在使用python 3.我試圖搜索的列表並不是每個插槽都嵌套的三元組。如何在三重嵌套列表中搜索?

下面是我寫的那種糟糕的方式,因爲某些原因不起作用。

HELLO = ["hello", "hi"] 
GOODBYE = ["goodbye", "bye"] 

POLITENESS = [HELLO, GOODBYE] 

FRUITS = ["apples", "bananas"] 
MEAT = ["pork", "chicken"] 

FOODS = [FRUITS, MEAT] 

random_Words = ["shoe", "bicycle", "school"] 


#Here is the triple nested list. 
VOCABULARY = [POLITENESS, FOODS, random_Words, "house"] 

knowWord = False 
userInput = input("say whatever") 

#this checks for userInput in triple nested lists 
#first it checks whether the first slot in vocabulary is nested, 
#if that's the case it checks if the lists wiithin vocabulary[i] is nested and goes on like that. 
#when finally it comes to a list that is not nested it checks for userInput in that list. 

for i in range(len(VOCABULARY)): 
    #if list item is not nested 
    if any(isinstance(j, list) for j in VOCABULARY[i]) == False: 
      #if userinput is inside a non-nested list 
      if userInput not in VOCABULARY[i]: 
       continue 
      else: 
       #if userInput is found 
       knowWord = True 
       break 
    #if list is nested 
    else: 
     continue 
    for k in range(len(VOCABULARY[i])): 
     if any(isinstance(l, list) for l in VOCABULARY[i][k]) == False: 
       if userInput not in VOCABULARY[i][k]: 
        continue 
       else: 
        knowWord = True 
        break 
     else: 
      continue 
     for m in range(len(VOCABULARY[i][k])): 
      if any(isinstance(n, list) for n in VOCABULARY[i][k][m]) == False: 
        if userInput not in VOCABULARY[i][k][m]: 
         continue 
        else: 
         knowWord = True 
         break 
      else: 
       continue 

if knowWord == True: 
    print("YES") 
else: 
    print("I don't know that word") 
+0

爲什麼不使用映射而不是'詞彙表'列表? –

+1

只是[壓扁列表](http://stackoverflow.com/a/953097)。你似乎不需要嵌套結構。您可能還想考慮將結果列表轉換爲集合,因此您可以在VOCABULARY查找中執行O(1)'userInput。 – ig0774

回答

0

爲了讓你的代碼工作,你可以簡單地刪除這些行:

#if list is nested 
else: 
    continue 

爲了使代碼更好,你可以使用遞歸。該功能發現,如果給定字裏面然而,許多嵌套列表中你有:

def findWord(word,l): 
    words = [] 
    lists = [] 
    for entry in l: 
     if isinstance(entry,list): 
      lists.append(entry) 
     else: 
      words.append(entry) 


    for w in words: 
     if w == word: 
      return True 

    for ls in lists: 
     if findWord(word,ls) == True: 
      return True 

    return False 



if findWord(userInput,VOCABULARY) == True: 
    print("YES") 
else: 
    print("I don't know that word") 
+0

完美,謝謝! –

0

如果你想使用嵌套列表中只有以下可能會幫助你,否則,解決上述拼合列表或轉換到Set也可以使用

def check(val): 
    for i in itertools.chain(VOCABULARY): 
     if val in i: 
      return True 
    return False