python - 当我清除我附加的原始列表时,为什么清除目标列表中的附加列表?
问题描述
我需要将 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 中附加的所有内容。为什么?
解决方案
正如 deceze 在评论中指出的那样,您总是使用相同的列表。
我不确定您为什么要这样做;只需在每次迭代时创建一个新列表。
def create_sublists(fname):
product = []
with ...
另请注意,您不必f
明确关闭;当 with 块退出时它会自动关闭,这就是 with 的全部意义。
推荐阅读
- emv - 无法通过 BP-Tools 验证密码
- java - 将变量名称永久转换为新类型
- docker - 将 docker 镜像拉到 Heroku 容器
- apache-spark - How to handle failure scenario in Spark write to orc file
- python - Pandas DataFrame identifiying rows that share column values according to a specific logic
- sql-server - How can I remove extra placeholders in this string in SQL?
- java - 在spring中通过组合RequestParam注解来封装注解默认值
- azureservicebus - 如何检查是否已经为 ServiceClient 实例注册了消息处理程序?
- file - 当上传成功完成或使用okhttp失败时,有没有办法生成回调?
- java - 如何在不使用新 url 的情况下在 WebView 上读取点击链接的 url?