2013-01-18 219 views
0

我正在開發一個定義測試程序(您輸入單詞,它們的部分演講內容和每個同義詞,然後測試它們)。問題我已經是與獲取字部分:Python:追加到列表

def get_word(): # this is in another function, that's why it is indented 
     import easygui as eg 
     word_info = eg.multenterbox(msg = 'Enter in the following information about each word.' 
           , title = 'Definition Tester' 
           , fields = ['Word: ', 'Part of Speech: ', 'Synonyms (separated by spaces): '] 
           , values = [] 
           ) 
     return word_info 
    for i in range(n): 
     my_list = get_word() 
     print my_list # for testing 
     word, pOS, synonyms = my_list[0], my_list[1], my_list[2] 
     word = word.capitalize() 
     synonyms = synonyms.split(', ') 
     words_list += word 
     print word # for testing 
     test_dict[word] = [pOS, synonyms] 
    print words_list # for testing 

但是,words_list結束了list(word)功能應用到他們之後是字(S)---我不知道爲什麼。

例如:如果唯一的單詞是'單詞',words_list原來是['w', 'o', 'r', 'd']。如果有兩個詞('狗','貓'),words_list原來是['d', 'o', 'g', 'c', 'a', 't']。 這是我的輸入(到get_word()):單詞:'myword',詞性:'n',同義詞:'同義詞,定義'。

這是輸出我得到:

['myword', 'n', 'synonym, definition'] 
Myword 
['M', 'y', 'w', 'o', 'r', 'd'] # Why does this happen? 

這是唯一的事情錯了我的計劃......如果我能得到關於如何解決這個問題,什麼是錯的一些投入,這將是更讚賞。謝謝!

+0

你能打印'word_info'嗎? –

+0

'my_list'等於'word_info',因爲函數'get_word()'返回'word_info','my_list'被設置爲返回值('my_list = get_word()')。 –

回答

6

這是因爲這行:

words_list += word 

+=名單上是在另一個列表加入的所有元素。碰巧,Python字符串也可以像字符列表一樣工作,因此您將每個字符添加到列表中作爲自己的元素。

你想這樣的:

words_list.append(word) 

這是添加單個元素進行到底。

0

瞎搞它之後,我想通了自己的問題,所以我想我應該把它放在這裏的人誰也有類似的東西:

而不是做words_list += word的,它應該是:words_list.append(word)

或者,這是我所做的,你可以這樣做:words_list += [word]。現在,word是一個list對象,所以它會添加到上一個列表中。

+0

'words_list + = [word]'不是非常pythonic。 '.append()'存在是有原因的。你應該接受Eevee的回答。 – That1Guy

+0

但它的工作。無論是否是Pythonic,它都能有效地完成工作,並且不會在'list + = [element]'或'list.append(element)'之間的內存和計算速度上產生顯着差異。 –