2012-11-27 374 views
0

*,因为我有几个错误我编辑了这个问题,请再次阅读* *指数 - 蟒蛇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']} 

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

谢谢!

回答

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

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

所以你可能会取代你的功能wi个简单:

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

使用enumerate

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

你能解释一下吗?它不适合我... – Yarden

+0

@Yarden代替使用'index'来查找'n',让'enumerate'通过迭代字符串来为你计算它。 – ecatmur

+1

@ecatmur:我喜欢这个答案的原始形式,它揭示了一个初学者可能没有意识到的有用功能,但他并没有为他做功课(也没有为他做他的思考)。唉,这还不够。 :( –

0

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

for i in range(1,len(a)): 
    print a[0:i+1] 
0
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) 

所以,你把你的功能 “纯”。

+0

'范围(len(word))'是错误的,应该先测试 – lenik

+0

现在工作正常。 – sureshvv

+0

仔细看,应该从'bi'开始,而不是从'b'开始,因为在你的情况下 – lenik