*,因为我有几个错误我编辑了这个问题,请再次阅读* *指数 - 蟒蛇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:我喜欢这个答案的原始形式,它揭示了一个初学者可能没有意识到的有用功能,但他并没有为他做功课(也没有为他做他的思考)。唉,这还不够。 :( –