首页 > 解决方案 > 当我清除我附加的原始列表时,为什么清除目标列表中的附加列表?

问题描述

我需要将 txt 文件的内容作为子列表附加到一个目标列表中:final_product 将是:

[[content file 1],[content of file2],[content of file 3]]

我试图用这段代码解决它:

import os
list_of_files = []
product = []
final_product = []

working_dir = r"U:/Work/"
os.chdir(working_dir)

def create_sublists(fname):
    with open(fname, 'r', encoding = 'ansi') as f:
        for line in f:
            product.append(line.strip()) #append each line from file to product
    final_product.append(product) #append the product list to final_product
    product.clear() #clear the product list
    f.close()

#create list of all files in the working directory
for file in os.listdir(working_dir):
    if file.endswith('.txt'):
        list_of_files.append(file)

for file in list_of_files:
    create_sublists(file)

print(final_product)

我认为它会以这种方式工作:第一个文件将其内容写入列表产品,此列表将附加到列表 final_product,列表产品将被清除,然后将附加第二个文件....但它创建了这个:

[ [], [], [], [], [], [] ].

当我不使用 product.clear() 时,它会以这种(错误)方式填充 final_product:

[[content_file1],[conetn_file1, content_file2],. 
[content_file1,content_file2, content_file3], ....]

然后,当我使用 product.clear() 时,它会删除 final_product 中附加的所有内容。为什么?

标签: python

解决方案


正如 deceze 在评论中指出的那样,您总是使用相同的列表。

我不确定您为什么要这样做;只需在每次迭代时创建一个新列表。

def create_sublists(fname):
    product = []
    with ...

另请注意,您不必f明确关闭;当 with 块退出时它会自动关闭,这就是 with 的全部意义。


推荐阅读