循环使用涉及列表中某些文件的过程?

时间:2018-07-05 06:28:30

标签: python loops

我有以下列表:

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等)中的每个dbound20194,20042,20161对的相应文件中执行这段代码该列表包含。

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循环并在方括号中使用该位置,但是它没有执行应有的操作。

1 个答案:

答案 0 :(得分:1)

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

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")

根据我的理解进行编辑