2017-06-29 49 views
0

當我嘗試將元組列表添加到另一個列表時,它變爲空。當我將元組列表添加到另一個列表時,它變爲空

tagged_sentences_list = [] 
for i in range (len(sentences)): 
    length_sentences = len(sentences[i].split(" ")) 

    del words_in_the_sentence[:] 
    del tagged_words[:] 

    for j in range (length_sentences): 
     length_words_in_sentence = len(sentences[i].split(" ")[j].split("/")[1:]) 

     part_of_the_speech = sentences[i].split(" ")[j].split("/")[1:] 
     word = sentences[i].split(" ")[j].split("/")[:1] 
     words_in_the_sentence.append(word) 

     zipped = zip(word,part_of_the_speech) 
     tagged_words.append(zipped) 

    tagged_sentences_list.append(tagged_words) 

正是在這一行:

tagged_sentences_list.append(tagged_words) 

終端打印

[[]] 

我要追加的元組列表到另一個列表。所以我會:

[[(a,b),(c,d)], [(d,e)]] 

你們中的任何人有任何想法爲什麼?由於

+0

'德爾tagged_words [:]'你刪除引用。你必須使用'copy'來創建新的列表。 – Brobin

回答

2

del tagged_words[:]清空列表,是的。

你有一個列表對象,你繼續填充和清空,並添加引用到另一個列表。您這裏創建副本:

tagged_sentences_list.append(tagged_words) 

創建新對象列表:

tagged_sentences_list = [] 
for i in range (len(sentences)): 
    length_sentences = len(sentences[i].split(" ")) 

    words_in_the_sentence = [] 
    tagged_words = [] 

    for j in range (length_sentences): 
     length_words_in_sentence = len(sentences[i].split(" ")[j].split("/")[1:]) 

     part_of_the_speech = sentences[i].split(" ")[j].split("/")[1:] 
     word = sentences[i].split(" ")[j].split("/")[:1] 
     words_in_the_sentence.append(word) 

     zipped = zip(word,part_of_the_speech) 
     tagged_words.append(zipped) 

    tagged_sentences_list.append(tagged_words) 

Python的名字都只是參考;您可能想了解Python的內存模型如何工作,我強烈建議Ned Batchelder's Facts and myths about Python names and values

你的代碼也做了很多冗餘分割。使用Python for循環爲for each constructs的事實;沒有必要生成索引時,你可以在列表本身的循環:

tagged_sentences_list = [] 
for sentence in sentences: 
    tagged_words = [] 

    for word in sentence.split(' '): 
     parts = word.split('/')[:2] 
     tagged_words.append(parts) 

tagged_sentences_list.append(tagged_words) 

請注意,有沒有必要使用zip();您所做的只是重新組合/拆分結果的第一個和第二個元素。

如果你使用list comprehensions,這可以進一步簡化爲:

tagged_sentences_list = [ 
    [word.split('/')[:2] for word in sentence.split(' ')] 
    for sentence in sentences] 
+0

是的,謝謝,這是正確的解決方案!祝你有美好的一天,非常感謝! – Sacramoni

1

試試這個:

tagged_sentences_list.append(tagged_words[:]) 

或者......

import copy 
tagged_sentences_list.append(copy.copy(tagged_words)) 

如果你在python3,你也可以嘗試

tagged_sentences_list.append(tagged_words.copy()) 

你目前的代碼做什麼是將列表附加到更大的列表中,然後使用del tagged_words[:]將其清除。

現在,由於引用是相同的,您最終會清除存儲在較大列表中的內容。

觀察:

>>> x = [] 
>>> y = [(1, 2), (3, 4)] 
>>> x.append(y) 
>>> id(x[0]) 
4433923464 
>>> id(y) 
4433923464 
>>> del y[:] 
>>> x 
[[]] 

你已經得到了空單,因爲你追加,然後清除原始。現在,這是當你的列表的副本會發生什麼:

>>> x = [] 
>>> y = [(1, 2), (3, 4)] 
>>> x.append(y[:]) 
>>> del y[:] 
>>> x 
[[(1, 2), (3, 4)]] 
+0

非常感謝!你是對的! – Sacramoni

相關問題