单词未显示在列表中



我有一个任务,我有一个列表(德语歌曲(,我的输入是歌曲前半部分的一个单词。 任务是从歌曲的前半部分取出一个词,看看它是否再次出现在后半部分,但我们必须以特定的方式进行。我们取单词的长度并跳到单词 2 很多次,然后获取单词 2 的长度并跳到单词 3 多次......如果我再次到达原始单词(我的输入(,我会停止。

我的代码的第一个问题是它总是走到列表的末尾,当它到达原始单词(输入(时不会停止。第二个问题是它不会将单词附加到列表中 2 次,它只附加一次。循环在到达输入或列表歌曲的末尾后应断开。

这是问题所在的代码(我认为(:if song[index] not in found_list:.

这是整个代码:

song = ["Es", "gingen", "zwei", "Parallelen",
"ins", "Endlose", "hinaus",
"zwei", "kerzengerade", "Seelen",
"und", "aus", "solidem", "Haus",
"Sie", "wollten", "sich", "nicht", "schneiden",
"bis", "an", "ihr", "seliges", "Grab",
"Das", "war", "nun", "einmal", "der", "beiden",
"geheimer", "Stolz", "und", "Stab",
"Doch", "als", "sie", "zehn", "Lichtjahre",
"gewandert", "neben", "sich", "hin", #End of the first half of the song, index: 42
"da", "wards", "dem", "einsamen", "Paare",
"nicht", "irdisch", "mehr", "zu", "Sinn",
"Warn", "sie", "noch", "Parallelen",
"Sie", "wußtens", "selber", "nicht", 
"sie", "flossen", "nur", "wie", "zwei", "Seelen",
"zusammen", "durch", "ewiges", "Licht",
"Das", "ewige", "Licht", "durchdrang", "sie",
"da", "wurden", "sie", "eins", "in", "ihm",
"die", "Ewigkeit", "verschlang", "sie",
"als", "wie", "zwei", "Seraphim"]

originalWord = input("Enter a word: ")
found_list = [] # The list for found words
index = song.index(originalWord) # Get the index of the first instance of "word"
wordCount = song.count(originalWord)

while True:
if wordCount <= 1:
print("Word appears only 1 time and therefore can't appear one more time")
break  
try:
if song[index] not in found_list:
found_list.append(song[index])
found_list.append(len(song[index]))
index += len(song[index]) 
except: 
break
print(found_list)

我解决了。我只需要将输入保存在一个变量中,然后比较保存的单词是否在列表中......

while True:
if wordCount <= 1:
print("Word appears only 1 time and therefore can't appear one more time")
break  
try:
found_list.append(song[index])
found_list.append(len(song[index]))
index += len(song[index]) 
if song[index] == originalWordSaved:
found_list.append(song[index])
found_list.append(len(song[index]))
print("Theorie works")
break
except:
print("Theorie doesn't work") 
break

最新更新