2012-11-27 372 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