微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

for 循环只会打印最后一个值而不是整个列表

如何解决for 循环只会打印最后一个值而不是整个列表

我正在尝试创建一个 for 循环,打印出列表中的每个项目,删除 .shp 并用projected.shp 替换它。但是,它只为列表中的最后一个值而不是所有元素创建一个 shapefile。我不确定我的 for 循环是否有问题,或者我是否没有正确使用 project_management。我的代码是:

import arcpy
import os

#establish spatial reference of selected feature class 
targetDesc= arcpy.Describe(targetFc)
targetSr = targetDesc.SpatialReference
targetSrName = targetSr.Name


arcpy.env.workspace = folderWorkspace
fcList = arcpy.ListFeatureClasses() 

# List current feature classes in folder
for fcCurrent in fcList:
    fcOut = os.path.splitext(fcCurrent)[0]
    print (fcOut + "_projected.shp")
    fcCurrentDesc = arcpy.Describe(fcCurrent)
    fcCurrentSr = fcCurrentDesc.SpatialReference
    fcCurrentSrName = fcCurrentSr.Name 
    
for fcCurrentSrName in fcCurrent: 
    if fcCurrentSrName == targetSr:  
               continue
    if fcCurrentSrName != targetSr: 
        print ("Error Matching Spacial Reference")
else: 
           print ("Spatial Reference Matching Succesful!")
# Print all of the geoprocessing messages
print(arcpy.GetMessages())

#Run Geoprocessing Tool
arcpy.Project_management(fcCurrent,fcOut +"_projected.shp",targetSr)

控制台返回:

CityBoundaries_projected.shp
CountyLines_projected.shp
Ferries_projected.shp
Populatedplaces_projected.shp
StateRoutes_projected.shp
Error Matching Spacial Reference
Error Matching Spacial Reference
Error Matching Spacial Reference
Error Matching Spacial Reference
Error Matching Spacial Reference
Error Matching Spacial Reference
Error Matching Spacial Reference
Error Matching Spacial Reference
Error Matching Spacial Reference
Error Matching Spacial Reference
Error Matching Spacial Reference
Error Matching Spacial Reference
Error Matching Spacial Reference
Error Matching Spacial Reference
Error Matching Spacial Reference
Spatial Reference Matching Succesful!
Start Time: Monday,May 24,2021 11:58:41 PM
Succeeded at Monday,2021 11:58:42 PM (Elapsed Time: 1.47 seconds)

但是在文件资源管理器中只创建 StateRoutes_projected.shp 而不是其他

解决方法

试试这个,

for fcCurrent in fcList:
    fcOut = os.path.splitext(fcCurrent)[0]
    print (fcOut + "_projected.shp")
    fcCurrentDesc = arcpy.Describe(fcCurrent)
    fcCurrentSr = fcCurrentDesc.SpatialReference
    fcCurrentSrName = fcCurrentSr.Name 
    
    for fcCurrentSrName in fcCurrent: 
        if fcCurrentSrName != targetSr: 
           print ("Error Matching Spacial Reference")
        else: 
           print ("Spatial Reference Matching Succesful!")
    arcpy.Project_management(fcCurrent,fcOut +"_projected.shp",targetSr)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。