字符串中字母的索引-python 2.7

字符串中字母的索引-python 2.7,python,string,list,function,indexing,Python,String,List,Function,Indexing,*我编辑这个问题是因为我有一些错误,请重新阅读*** 我正在构建一个函数,该函数使用单词构建字典,例如: {'b': ['b', 'bi', 'bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday'], 'bi': ['bi', 'bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday'], 'birt': ['birt', 'birth', 'birthd', 'birthda', 'bi

*我编辑这个问题是因为我有一些错误,请重新阅读***

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

{'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
它对“生日”这样的词很有用,但当我有一封重复的信时,我有一个问题。。。例如,“你好”

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

谢谢大家!

使用:


假设变量a是一个简单的字符串(例如,“生日”、“你好”),您可以使用:

for i in range(1,len(a)):
    print a[0:i+1]
给予

因此,您可以用简单的以下内容替换您的函数:

prefix_dict[word] = [word[:i] for i in range(2,len(word)+1)]
更好的是:

def get_words(word):
    return [ word[:n+1] for n in range(1, len(word)) ]
prefix_dict[word] = get_words(word)

因此,您可以保持函数的“纯”。

@Yarden没有使用
索引
来查找
n
,而是让
枚举
通过迭代字符串来为您计算。@ecatmur:我喜欢这个答案的原始形式,它揭示了一个初学者可能不知道的有用功能,但没有为他做功课(而且没有为他着想)。唉,这还不够。:(仔细看,应该从
bi
开始,而不是从
b
开始,因为在您的案例中,已修复为不包含单个字符
a = 'birthday'
[a[:i] for i in range(2,len(a)+1)]
['bi', 'bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday']
prefix_dict[word] = [word[:i] for i in range(2,len(word)+1)]
def add_prefixs(word, prefix_dict):
    prefix_dict[word] = [ word[:n+1] for n in range(1, len(word)) ]
def get_words(word):
    return [ word[:n+1] for n in range(1, len(word)) ]
prefix_dict[word] = get_words(word)