如果您得到一个名称列表,其中包含要分组的特定键(DAY-VARIABLE-DIRECTION),例如:
fileList: ['26.cloud_in.des.11.tif', '26.cloud_in.des.14.tif', '26.cloud_in.des.2.tif', '26.cloud_in.des.5.tif', '26.cloud_in.des.8.tif', '26.LST.asc.16.tif', '26.LST.des.1.tif', '26.LST.des.10.tif', '26.LST.des.13.tif', '26.LST.des.4.tif', '26.LST.des.7.tif', '26.NDVI.des.12.tif', '26.NDVI.des.15.tif', '26.NDVI.des.3.tif', '26.NDVI.des.6.tif', '26.NDVI.des.9.tif']
可以将N个键用作以列表为值的字典的键。你知道吗
这是我的密码:
groupResult = {}
for file in filesList:
day = file.split('.')[0]
prod = file.split('.')[1]
oDir = file.split('.')[2]
key = day+"-"+prod+"-"+oDir
if key in groupResult:
currList = groupResult[key]
currList.append(file)
groupResult[key] = currList
else:
groupResult[key] = [file]
结果是:
groupResult: {'26-cloud_in-des': ['26.cloud_in.des.11.tif', '26.cloud_in.des.14.tif', '26.cloud_in.des.2.tif', '26.cloud_in.des.5.tif', '26.cloud_in.des.8.tif'], '26-LST-asc': ['26.LST.asc.16.tif'], '26-LST-des': ['26.LST.des.1.tif', '26.LST.des.10.tif', '26.LST.des.13.tif', '26.LST.des.4.tif', '26.LST.des.7.tif'], '26-NDVI-des': ['26.NDVI.des.12.tif', '26.NDVI.des.15.tif', '26.NDVI.des.3.tif', '26.NDVI.des.6.tif', '26.NDVI.des.9.tif']}
这是最好的处理方法吗?你知道吗
尝试使用
setdefault
:或者使用
defaultdict
:现在两种情况都出现了:
输出:
这是一种使用regex的方法。你知道吗
例如:
输出:
你可以试试
itertools.groupby
:或者
相关问题 更多 >
编程相关推荐