2016-05-15 71 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