Skip to main content
 首页 » 编程设计

python之使用涉及列表中某些文件的过程进行循环

2024年12月31日13落叶无声

我有以下列表:

grouped_shapefiles,每个文件夹中都有这些文件目录:(pst 和 dbound 对)。

[['C:\\Users\\user\\Desktop\\eff\\20194\\DBOUND\\DBOUND.shp', 
  'C:\\Users\\user\\Desktop\\eff\\20194\\PST\\PST.shp'], 
 ['C:\\Users\\user\\Desktop\\eff\\20042\\DBOUND\\DBOUND.shp', 
  'C:\\Users\\user\\Desktop\\eff\\20042\\PST\\PST.shp'], 
 ['C:\\Users\\user\\Desktop\\eff\\20161\\DBOUND\\DBOUND.shp', 
  'C:\\Users\\user\\Desktop\\eff\\20161\\PST\\PST.shp'], 
 ['C:\\Users\\user\\Desktop\\eff\\20029\\DBOUND\\DBOUND.shp', 
  'C:\\Users\\user\\Desktop\\eff\\20029\\PST\\PST.shp'], 
 ['C:\\Users\\user\\Desktop\\eff\\20008\\DBOUND\\DBOUND.shp', 
  'C:\\Users\\user\\Desktop\\eff\\20008\\PST\\PST.shp']] 

我想制作一个 for 循环,在每个文件夹中的每个 pst 和 dbound 对的相应文件中执行这段代码 (20194,20042 ,20161,etc...) 列表包含。

import geopandas as gpd 
import pandas 
#pst = gpd.read_file(r'C:\Users\user\Desktop\New folder1\PST')#this is not needed in the final because it takes the path by it self 
#dbound = gpd.read_file(r'C:\Users\user\Desktop\New folder1\DBOUND')#same here 
dbound.reset_index(inplace=True) 
wdp = gpd.sjoin(pst, dbound, how="inner", op='within')#each dbound and pst from every folder 
wdp['DEC_ID']=wdp['index'] 

我只是想知道如何制作 for 循环来执行代码在文件中应该执行的操作。我已经尝试使用 for 循环并使用括号中的位置,但它没有做它应该做的事情。

请您参考如下方法:

不确定我是否正确理解了您的问题,您是否尝试成对遍历列表中的项目?如果是这样,那就很简单了:

for i in grouped_shapefiles: 
    pst = gpd.read_file(i[0]) 
    dbound = gpd.read_file(i[1]) 
    if i[0].split("\\")[-3] == i[1].split("\\")[-3]: 
        dbound.reset_index(inplace=True) 
        wdp = gpd.sjoin(pst, dbound, how="inner", op='within') 
        wdp['DEC_ID'] = wdp['index'] 
    else: 
        print ("Folder pairs mismatch") 

根据我的理解编辑