社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python for loop只将最后一个列表作为值追加

Sascha • 4 年前 • 346 次点击  

我在一个目录中循环,希望将文件夹中的所有文件作为列表存储在字典中,其中每个键都是一个文件夹和文件列表的值。

循环中的第一次打印正好显示了我所期望的输出。

但是,第二次打印显示空值。

类初始化后的第三次打印将最后一个子文件夹的列表显示为每个键的值。

我忽略了什么或做错了什么?

class FileAndFolderHandling() :

    folders_and_files = dict()


    def __init__(self) :
        self.getSubfolderAndImageFileNames()


    def getSubfolderAndImageFileNames(self) :

        subfolder = ""
        files_in_subfolder = []

        for filename in glob.iglob('X:\\Some_Directory\\**\\*.tif', recursive=True) :

            if not subfolder == os.path.dirname(filename) and not subfolder == "" :
                print(subfolder + "  /  /  " + str(files_in_subfolder))
                self.folders_and_files[subfolder] = files_in_subfolder   
                files_in_subfolder.clear()
                print(self.folders_and_files)

            subfolder = os.path.dirname(filename) # new subfolder
            files_in_subfolder.append(os.path.basename(filename))



folder_content = FileAndFolderHandling()

print(folder_content.folders_and_files)
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/41047
 
346 次点击  
文章 [ 3 ]  |  最新文章 4 年前
Ben Brown
Reply   •   1 楼
Ben Brown    5 年前

你在清理阵列,从我所看到的…

files_in_subfolder.clear()

删除它,并确保在执行任何清除操作之前,您的值被添加到folders\u and\u files变量中。

Rodrigo De Rosa
Reply   •   2 楼
Rodrigo De Rosa    5 年前

看起来你的问题是你实际上一直在使用 相同的 名单。

定义 files_in_subfolder = [] 创建一个列表,并在刚刚定义的变量中为该列表分配一个指针。所以当你分配 self.folders_and_files[subfolder] = files_in_subfolder 您只将指向列表的指针(在每次迭代中都是相同的)存储在字典中,而不是实际的列表中。

以后,当你这样做的时候 files_in_subfolder.clear() 您正在清除指针所指向的列表,并因此清除字典中的所有条目(因为它始终是同一个列表)。

为了解决这个问题,我建议您创建 新的 为字典中的每个不同条目列出列表,而不是为每次迭代清除它。这是,移动 files_in_subfolder 从圈外到圈内。

希望有帮助!

quamrana mzoll
Reply   •   3 楼
quamrana mzoll    5 年前

听起来你在找 defaultdict .

我修改了你的代码如下:

import glob, os
from collections import defaultdict

class FileAndFolderHandling() :
    folders_and_files = defaultdict(list)

    def __init__(self) :
        self.getSubfolderAndImageFileNames()

    def getSubfolderAndImageFileNames(self) :
        for filename in glob.iglob(r'C:\Temp\T\**\*.txt', recursive=True) :
            # print(filename)
            subfolder = os.path.dirname(filename)
            self.folders_and_files[subfolder].append(os.path.basename(filename))


folder_content = FileAndFolderHandling()

print(dict(folder_content.folders_and_files))

Output:
{'C:\\Temp\\T': ['X.txt'], 'C:\\Temp\\T\\X': ['X1.txt', 'X2.txt'], 'C:\\Temp\\T\\X2': ['X1.txt']}

这个 defaultdict(list) 为添加的每个新密钥创建一个新列表。这似乎是你希望在代码中发生的事情。