在 Python 中,如何在列表中的每个项目/字符串中搜索和计数/打印一组特定的字符



>我最终需要显示列表中文件以 .shp 结尾的所有项目。所以我需要能够单独索引每个列表项。有什么建议吗?

这是我到目前为止所拥有的:

folderPath = r'K:geog 173LabData'
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

您可以使用列表推导式和str.endswith()轻松做到这一点:

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

你能指定所需的输出格式吗?这将使工作变得容易...

一个可能的答案是

fileList = [f for f in os.listdir('K:geog 173LabData') 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)  

最新更新