当我尝试将元组列表添加到另一个列表时,它变为空。
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 :(得分: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]
答案 1 :(得分: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)]]