Python 为什么在清除附加的原始列表时,目标列表中的附加列表被清除?
我需要将txt文件的内容作为子列表附加到一个目标列表中: 最终产品将是:Python 为什么在清除附加的原始列表时,目标列表中的附加列表被清除?,python,Python,我需要将txt文件的内容作为子列表附加到一个目标列表中: 最终产品将是: [[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):
[[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)
我认为它将以这种方式工作:第一个文件将其内容写入列表产品,该列表将被追加到列表最终产品中,列表产品将被清除,然后追加到第二个文件中。。。。
但它创造了这一点:
[ [], [], [], [], [], [] ].
当我不使用product.clear()时,它以以下(错误)方式填充最终产品:
然后,当我使用product.clear()时,它会删除最终产品中附加的所有内容。为什么?正如deceze在评论中指出的,您总是使用相同的列表 我不知道你为什么要这样做;只需在每次迭代中创建一个新列表
def create_sublists(fname):
product = []
with ...
还要注意的是,您不必显式地关闭
f
;当with块退出时,它会自动关闭,这就是with的全部要点。只有一个product
list对象,您会不断追加它。都是一张单子!python的新特性,所以我不这样做是愚蠢的。你解决了我的问题。非常感谢!:)在可能的情况下(由于时间限制),我会接受你的回答
def create_sublists(fname):
product = []
with ...