在重复字母上使用`.index()`

Yar*_*den 1 python dictionary autocomplete

我正在构建一个用单词构建字典的函数,例如:

{'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']}
Run Code Online (Sandbox Code Playgroud)

这就是它的样子:

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
Run Code Online (Sandbox Code Playgroud)

它适用于像"生日"这样的单词,但是当我有一个重复的字母时,我有一个问题......例如,"你好".

{'h': ['h', 'he', 'he', 'hell', 'hello'], 'hell': ['hell', 'hello'], 'hello': ['hello'], 'he': ['he', 'he', 'hell', 'hello']}
Run Code Online (Sandbox Code Playgroud)

我知道这是因为索引(python选择字母第一次出现的索引)但我不知道如何解决它.是的,这是我的作业,我真的想向你们学习:)

Mar*_*ers 5

你已经循环了这个词; 而不是使用.index()保持计数器.Python让你很容易; 使用enumerate()功能:

for n, letter in enumerate(word):
    if n==0:
        lst.append(word[0])
    else:
        lst.append(word[0:n])
Run Code Online (Sandbox Code Playgroud)

现在你不再使用letter变量虽然如此,只是range(len(word)改为:

for n in range(len(word)):
    if n==0:
        lst.append(word[0])
    else:
        lst.append(word[0:n])
Run Code Online (Sandbox Code Playgroud)

我们可以将其简化为列表理解:

lst = [word[0:max(n, 1)] for n in range(len(word))]
Run Code Online (Sandbox Code Playgroud)

注意max()那里; 而不是测试if是否n为0,我们1为切片设置最小值.

然后,您再次删除第一个条目(因为它与第二个结果相同)添加完整的单词,只需将1添加到n计数器:

lst = [word[0:n+1] for n in range(len(word))]
Run Code Online (Sandbox Code Playgroud)

函数的后半部分可以enumerate()有效地使用该函数,而不是.index():

for b, elem in enumerate(lst):
    prefix_dict[elem]=lst[b:]
Run Code Online (Sandbox Code Playgroud)

现在你的功能更简单了; 请注意,由于您在原地操作,因此无需返回 prefix_dict:

def add_prefixs(word, prefix_dict):
    lst = [word[0:n+1] for n in range(len(word))]
    for b, elem in enumerate(lst):
        prefix_dict[elem]=lst[b:]
Run Code Online (Sandbox Code Playgroud)