当前位置: 动力学知识库 > 问答 > 编程问答 >

index of a letter in string - python 2.7

问题描述:

*I'm editing this question because I had a few mistakes, please read again**

I'm building a function that builds a dictionary with words, such as:

{'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']}

This is what it looks like:

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

It works great for words like "birthday", but when I have a letter that repeats itself, I have a problem... for example, "hello".

{'h': ['h', 'he', 'he', 'hell', 'hello'], 'hell': ['hell', 'hello'], 'hello': ['hello'], 'he': ['he', 'he', 'hell', 'hello']}

I know it's because of the index (python chooses the index of the first time the letter appears) but I do not know how to solve it. Yes, this is my homework and I'm really trying to learn from you guys :)

Thank you!

网友答案:
a = 'birthday'
[a[:i] for i in range(2,len(a)+1)]

gives

['bi', 'bir', 'birt', 'birth', 'birthd', 'birthda', 'birthday']

so you may replace your function with simple:

prefix_dict[word] = [word[:i] for i in range(2,len(word)+1)]
网友答案:

Use enumerate:

for n, letter in enumerate(word):
    if n==0 or n==1:
        continue
    else:
        lst.append(word[0:n])
网友答案:

Assuming variable a is a simple string(eg, "birthday", "hello"), you could use:

for i in range(1,len(a)):
    print a[0:i+1]
网友答案:
def add_prefixs(word, prefix_dict):
    prefix_dict[word] = [ word[:n+1] for n in range(1, len(word)) ]

Better yet:

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

So you keep your function "pure".

分享给朋友:
您可能感兴趣的文章:
随机阅读: