在Python中,如何在lis中的每个项/字符串中搜索和计数/打印特定的字符集

2024-09-30 20:36:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我最终需要显示列表中所有以.shp结尾的项目。所以我需要能够分别索引每个列表项。有什么建议吗?你知道吗

到目前为止,我的情况是:

folderPath = r'K:\geog 173\LabData'

import os
import arcpy

arcpy.env.workspace = (folderPath)
arcpy.env.overwriteOutput = True

fileList = os.listdir(folderPath)
print fileList


"""Section 2: Identify and Print the number
and names of all shapefiles in the file list:"""

numberShp = 0

shpList= list()

for fileName in fileList:
    print fileName

fileType = fileName[-4:]
print fileType

if fileType == '.shp':
    numberShp +=1
    shpList.append(fileName)

print shpList
print numberShp

Tags: andtheimportenv列表osfilenamefiletype
2条回答

请指定所需的输出格式。那会使工作变得容易。。。你知道吗

一个可能的答案是

fileList = [f for f in os.listdir('K:\geog 173\LabData') if f.endswith('.shp')]

for i,val in enumerate(fileList):
    print '%d. %s' %(i,val)  

#If u want to print the length of the list again...
print len(fileList)  

使用list comprehensions^{}可以很容易地做到这一点:

shpList = [fileName for fileName in fileList if fileName.endswith('.shp')]

print shpList
print len(shpList)

相关问题 更多 >