在 Python 中的 for 循环中匹配字符串

Matching strings in for loop in Python

我有一个 pandas 数据框 df 看起来像这样

df = {'Regions': {0: 'REGION1', 1: 'REGION2'}, 'x': {0: '1249-43,1269-12,1280-12', 1: '1267-12,1269-12,1280-12'}}

以及名为 rasters

的光栅文件列表
rasters = 'SI_1206-33_50cm.tif', 'SI_1249-43_50cm.tif', 'SI_1269-12_50cm.tif', 'SI_1267-12_50cm.tif', 'SI_3865-17_50cm.tif' 

我想做的是创建一个新列表,其中包含 rasters 中与每个区域 df.x 中的字符串相匹配的所有条目。

for index, row in df.iterrows():
    region = row['Regions']
    tiffs = row['x']
    rasterlist = []
    for raster in rasters:
        if raster in tiffs:
            rasterlist = rasterlist.append(raster)
            print(rasterlist)

因此,在对栅格进行迭代时,我试图在第一次迭代中获取一个 rasterlist,其中包含 REGION1 的 'SI_1249-43_50cm.tif''SI_1269-12_50cm.tif',在第二次迭代中获取一个 rasterlist 仅包含 REGION2 的 'SI_1267-12_50cm.tif'。我想将列表 rasterlist 用作输入,以便使用 arcpy 中的 MosaicToNewRaster_management 函数进行进一步处理。

模式匹配似乎不适用于此代码,每次迭代我都会得到一个空的 rasterlist 变量。我假设是这种情况,因为 df.x 中的不同列表项由逗号分隔,并且 in 函数似乎不起作用。这是我卡住的地方,希望得到一些意见。

你查错方向了。您正在使用

if raster in tiffs

tiffs 就像 '1249-43,1269-12,1280-12' 一样,其中显然有 none 个光栅。您需要拆分 tiff 列表并在相反方向检查才能看到如果任何 tiffs 在光栅中。

tiffs = row['x'].split(',')
raster_list = []
for raster in rasters:
    for tiff in tiffs:
        if tiff in raster:
            raster_list.append(raster)
            # Assuming each tiff matches with only one raster
            # you can break to save some time here.
            break
print(raster_list)

如果您能告诉我们更多关于光栅和 tiff 之间映射的信息,那么使用 dicts 或 sets 可能会更有效。