如何在重复文件列表中创建列表?

时间:2014-03-23 00:12:30

标签: python list duplicates

我有一段代码可以在目录中创建一个栅格文件列表:

import arcpy, os

workspace = r'C:\temp'

# Get a list of all files in all subfolders
rasters = []
for dirpath, dirnames, filenames in arcpy.da.Walk(workspace,
                                                  topdown = True,
                                                  datatype="RasterDataset"):
    for filename in filenames:
        rasters.append(os.path.join(dirpath, filename))

生成.tif文件列表:

[r'C:\temp\block1\fileA.tif', r'C:\temp\block1\fileB.tif', r'C:\temp\block2\fileA.tif', r'C:\temp\block2\fileB.tif']

如何生成包含重复文件名的列表列表,如下例所示?

[[r'C:\temp\block1\fileA.tif', r'C:\temp\block2\fileA.tif'], [r'C:\temp\block1\fileB.tif', r'C:\temp\block2\fileB.tif']]

1 个答案:

答案 0 :(得分:4)

收集字典中的文件,以基本名称键入; collections.defaultdict() object使这更容易:

from collections import defaultdict

rasters = defaultdict(list)

for dirpath, dirnames, filenames in arcpy.da.Walk(workspace,
                                                  topdown = True,
                                                  datatype="RasterDataset"):
    for filename in filenames:
        rasters[filename].append(os.path.join(dirpath, filename))

rasters = rasters.values()

这会将filename的路径分组到列表中; rasters.values()构建您想要的列表列表。