*,因爲我有幾個錯誤我編輯了這個問題,請再次閱讀* *指數 - 蟒蛇2.7
我建立一個功能與構建字的字典,如:
{'b': ['b', 'bi', 'bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday'], 'bi': ['bi', 'bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday'], 'birt': ['birt', 'birth', 'birthd', 'birthda', 'birthday'], 'birthda': ['birthda', 'birthday'], 'birthday': ['birthday'], 'birth': ['birth', 'birthd', 'birthda', 'birthday'], 'birthd': ['birthd', 'birthda', 'birthday'], 'bir': ['bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday']}
這是什麼樣子:
def add_prefixs(word, prefix_dict):
lst=[]
for letter in word:
n=word.index(letter)
if n==0:
lst.append(word[0])
else:
lst.append(word[0:n])
lst.append(word)
lst.remove(lst[0])
for elem in lst:
b=lst.index(elem)
prefix_dict[elem]=lst[b:]
return prefix_dict
它適用於像「生日」這樣的文字,但是當我有一封重複自己的信件時,我遇到了一個問題......例如「hello」。
{'h': ['h', 'he', 'he', 'hell', 'hello'], 'hell': ['hell', 'hello'], 'hello': ['hello'], 'he': ['he', 'he', 'hell', 'hello']}
我知道這是因爲索引(蟒蛇選擇第一次出現信件的索引),但我不知道如何解決它。是的,這是我的家庭作業,我真的很想向你們學習:)
謝謝!
你能解釋一下嗎?它不適合我... – Yarden
@Yarden代替使用'index'來查找'n',讓'enumerate'通過迭代字符串來爲你計算它。 – ecatmur
@ecatmur:我喜歡這個答案的原始形式,它揭示了一個初學者可能沒有意識到的有用功能,但他並沒有爲他做功課(也沒有爲他做他的思考)。唉,這還不夠。 :( –