簡體   English   中英

當我將元組列表追加到另一個列表時,它變為空

[英]When I append list of tuples to another list it becomes empty

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

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)]]

你們當中有人知道為什么嗎? 謝謝

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 關於Python名稱和值事實和神話

您的代碼也做了很多多余的拆分。 利用Python for循環適用於每個結構的事實; 當您可以遍歷列表本身時,無需生成索引:

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() 您要做的就是重新組合/拆分結果的第一個和第二個元素。

如果要使用列表推導 ,則可以進一步簡化為:

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

嘗試這個:

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)]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM