2016-05-15 3 views
0

私は、Pythonでトリプルネストされたリストを検索しようとしています。私はうまくいかないような方法を思いついた。どのようにこれを効果的に行うのですか?私はpython 3を使用しています。私が検索しようとしているリストは、すべてのスロットにnececarilyトリプルネストされていません。トリプルネストされたリストをどのように検索しますか?

これは、私が何らかの理由で動作しないと書いた悪い汚い方法です。

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)。ネストされた構造は必要ないと思われます。結果リストをセットに変換することも考えてみてください。そうすれば、O(1) 'userInput in VOCABULARY'ルックアップを行うことができます。 – 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

あなただけにして、以下のネストされたリストを使用したい場合は、あなたを助けるかもしれない、そうでない場合は、解決策は、リストを平らにするために、上述のかへの変換しますセットも使用できます

def check(val): 
    for i in itertools.chain(VOCABULARY): 
     if val in i: 
      return True 
    return False 
関連する問題