*我正在编辑这个问题,因为我有一些错误,请再阅读**
我正在构建一个函数,用词建立一个字典,比如:
{'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它适用于像“生日”这样的词,但是当我有一封重复的信时,我遇到了一个问题,比如“你好”。
{'h': ['h', 'he', 'he', 'hell', 'hello'], 'hell': ['hell', 'hello'], 'hello': ['hello'], 'he': ['he', 'he', 'hell', 'hello']}我知道这是因为索引(python选择了第一次出现这个字母的索引),但我不知道如何解决它。是的,这是我的家庭作业,我真的很想向你们学习:)
谢谢!