Python 执行复杂的嵌套循环?
我有一个列表“Python 执行复杂的嵌套循环?,python,loops,Python,Loops,我有一个列表“shapelist”,其中有许多要使用的目录。 这个循环有很多功能,在这个过程中,我必须添加另一个循环,将坐标系分配给一些文件。正确的方法是什么 #This is the initial loop for i in shapelist: arcpy.FeatureToLine_management([i] ,i.replace('ASTENOT.shp', 'ASTENOT_lines')) #many more lines with functions #
shapelist
”,其中有许多要使用的目录。
这个循环有很多功能,在这个过程中,我必须添加另一个循环,将坐标系分配给一些文件。正确的方法是什么
#This is the initial loop
for i in shapelist:
arcpy.FeatureToLine_management([i] ,i.replace('ASTENOT.shp', 'ASTENOT_lines'))
#many more lines with functions
#at some point I have to add coordinate system information to exported files
#how do I do that in this loop without creating perplexing results?
我想在某个地方添加这段代码,用于坐标系赋值
#Finds and stores to a list the files that need the coordinate system assignment
rootfolder = r'C:\Users\user\Desktop\etg'
import os
newlist = []
for path, subdirs, files in os.walk(rootfolder):
for name in files:
if name==('centerline.shp'):
newlist.append(os.path.join(path, name))
newlist
现在包含需要坐标系指定的文件
#follows the loop that does the assignment
for i in newlist:
... sr = arcpy.SpatialReference(2100)
... arcpy.DefineProjection_management(i, sr)
如何将所有这些添加到初始循环中?由于在没有输入数据和预期输出的情况下很难测试问题的解决方案,而且我从未使用过ArcGIS,因此我只能推测您想要做什么:
import pathlib
# Root directory of where your files resides
rootfolder = pathlib.Path(r'C:\Users\user\Desktop\etg')
# Get all files named 'centerline.shp' in this directory and all its
# sub-directories
newlist = rootfolder.glob('**/centerline.shp')
# Define a SpatialReference (?)
spatial_reference_to_use = arcpy.SpatialReference(2100)
# Assign a defined projection to all the files in newlist (?)
for file_to_assign in newlist:
arcpy.DefineProjection_management(str(file_to_assign),
spatial_reference_to_use)
# From the input file names (in newlist), define
# the output file names (?)
newlist_out_features = [current_file.with_name('ASTENOT_lines')
for current_file in newlist]
# Change features to lines for all the files in newlist (?)
for (current_shape_file, current_out_features) in zip(newlist,
newlist_out_features):
arcpy.FeatureToLine_management([str(current_shape_file)],
str(current_out_features))
这是你想做的事吗?如果不是,你必须更好地解释你想做什么。
sr
被分配到那里。它是一个包含空间引用的变量,对于需要它的参数中的下一行非常有用。希望现在清楚。显然这三个循环彼此独立,为什么你认为它们要复杂嵌套?因为它们必须在第一个循环内“因为它们必须在第一个循环内”这是重复的。第二个循环使用一个常量根(不取决于第一个循环),第三个循环使用从第二个循环生成的信息,但不需要嵌套在第二个循环中(可以编写一个循环来查找文件并更新它们)。如果你不提供更多的上下文,我不明白为什么第二个和第三个循环必须嵌套在第一个循环中。它必须放在第一个for
循环过程中的某个点上,因为结果将在另一个函数中使用(仍然在第一个for循环中)。这是把它放在这个位置的主要原因。