唯一列表是否可以接受小写和大写条目

时间:2013-05-21 07:13:27

标签: python list unique

我的脚本记录有关目录和子目录中所有唯一文件类型的信息。在创建唯一文件扩展名列表的过程中,当前代码认为jpg,Jpg和JPG是相同的,因此它只包含List中的一个。如何包含所有三个或更多差异?

for root, dirs, files in os.walk(SourceDIR, topdown=False):
    for fl in files:
        currentFile=os.path.join(root, fl)
        ext=fl[fl.rfind('.')+1:]
        if ext!='':
            if DirLimiter in currentFile:
                List.append(currentFile)
                directory1=os.path.basename(os.path.normpath(currentFile[:currentFile.rfind(DirLimiter)]))
                directory2=(currentFile[len(SourceDIR):currentFile.rfind('\\'+directory1+DirLimiter)])
                directory=directory2+'\\'+directory1
                if directory not in dirList:
                    dirCount+=1
                    dirList.append(directory)


        if ext not in extList:
          extList.append(ext)

完整的脚本在stackexchange上的这个问题中:Recurse through directories and log files by file type in python

感谢JennaK进一步调查,我发现jpg报告中的输入实际上在文件中有JPG和jpg,如下所示。

> 44;X:\scratch\project\Input\Foreshore and Jetties Package
> 3\487679 - Jetty\IMG_1630.JPG;3755267
> 45;X:\scratch\project\Input\Foreshore and Jetties Package
> 3\487679 - Jetty\IMG_1633.JPG;2447135
> 1;X:\scratch\project\Input\649701 - Hill
> Close\2263.jpg;405328 2;X:\scratch\project\Input\649701 - Hill Close\2264.jpg;372770

所以它首先得到了所有JPG文件的详细信息,然后是jpg文件并将它们放在一个报告中,这实际上比2报告更方便。我想我的编程比我想象的要好: - )

1 个答案:

答案 0 :(得分:2)

不,对于listin运算符检查是否相等,并且字符串在使用相同的情况时仅相互相等。

您可以在此处使用集合,并在其中存储所有directory.lower()值。对于作为列表的成员资格测试,集合(很多)更快:

directories = set()
extensions = set()

for root, dirs, files in os.walk(SourceDIR, topdown=False):
    # ...
        # no need to use `directory.lower() in directories`, just update the set:
        directories.add(directory.lower())

    # ...
    extensions.add(ext.lower())

dirCount变量以后很容易派生出来:

dirCount = len(directories)

您还想查看os.path提供的功能,尤其是os.path.splitext()os.path.relpath()os.path.join()函数。

循环中的文件处理可以简化很多;一个:

for fl in files:
    filename = os.path.join(root, fl)
    base, ext = os.path.splitext(filename)
    if ext:
       List.append(filename)
       directory = os.path.relpath(filename, SourceDir)
       directories.add(directory.lower())
       extensions.add(ext)

请注意,我在这里使用 os.path.relpath();您的os.path.basename()os.path.normpath()舞蹈加分隔符等等不必要地复杂化。

现在,在各行之间进行阅读,似乎您只想将扩展视为只是该部分的情况。

在这种情况下,请从os.path.splitext()

的结果中自行构建一个新文件名
base, ext = os.path.splitext(filename)
normalized_filename = base + ext.lower()

现在normalized_filename是扩展名降低的文件名,因此您可以根据需要在集合中使用该值。