Python:在函数外部调用列表时,追加到函数中的列表不会返回任何值



感谢您花时间阅读本文。我遇到了一个问题,在函数外调用列表会返回空值。我想做的是查看文档,如果该文档中的单词也在预定义的列表中(或不在(,则创建一个包含1(和0(的列表。接下来,我想遍历多个文档,并制作一个列表列表。我认为下面的代码示例将为我试图实现的目标提供更多的上下文。

输入:

import nltk
company_list = ["This is a company that does excavation",
"Last financial quarter was bad ",
"This year we are going be exceed the projected returns."]
middle_list = []
vector = []
final_list = []
bag = ["year", "excavation", "quarter", "returns"]

def test_function():
counter = 0
for company in company_list:
tokenize = nltk.word_tokenize(company)
# eliminate the duplicates
tokenize = set(tokenize)
# make all the words lower case
for word in tokenize:
word = word.lower()
middle_list.append(word)
for word in bag:
if word in middle_list:
x = 1
else:
x = 0
vector.append(x)
# clear the middle list so that a new company's words can be put inside an empty list
middle_list.clear()
counter += 1
print("Vector values: At", counter, vector)
final_list.append(vector)
print("List values: At", counter, final_list)
# clear the vector so that for each company it starts with an empty list
vector.clear()
return final_list

test_function()
print("list outside function: ", final_list)

输出:

Vector values: At 1 [0, 1, 0, 0]
List values: At 1 [[0, 1, 0, 0]]
Vector values: At 2 [0, 0, 1, 0]
List values: At 2 [[0, 0, 1, 0], [0, 0, 1, 0]]
Vector values: At 3 [1, 0, 0, 1]
List values: At 3 [[1, 0, 0, 1], [1, 0, 0, 1], [1, 0, 0, 1]]
list outside function:  [[], [], []]

预期结果:[0,1,0,0],[0,0,1,0],[1,0,0,1]

正如你所看到的,有两个问题:

1( 当我在函数中打印列表时,它会返回一个向量列表,但向量是重复的(我不希望(2( 当我想在函数外打印列表时,它会返回一个由3个列表组成的列表,但每个列表都是空的。

感谢您的时间和帮助!

我看过你的代码,如果你在vector.clear((之后添加一个print,我想你会看到发生了什么。

Final_list只包含对向量的引用,所以当您清除它时,它也会清除Final_list中的内容。

更改

final_list.append(vector)

final_list.append(vector.copy())

最新更新