[英]How do you search in triple nested lists?
我正在嘗試搜索python中的三重嵌套列表。 我想出了一種超級混亂的方式,這種方式行不通。 您如何有效地做到這一點? 我正在使用python3。我嘗試搜索的列表不一定在每個插槽中都是三層嵌套的。
這是我寫的一團糟的雜亂方式,由於某種原因它不起作用。
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")
要使代碼正常工作,您可以刪除以下幾行:
#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")
如果您只想使用嵌套列表,那么下面的內容可能會對您有所幫助,否則,也可以使用上面提到的將列表展平或轉換為Set的解決方案
def check(val):
for i in itertools.chain(VOCABULARY):
if val in i:
return True
return False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.