在Python中循环数据集

2024-09-29 23:18:56 发布

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

我正在尝试编写一个Python脚本,它将在多个数据库上执行相同的操作。有太多的东西我无法手工输入,所以我想写一个脚本来循环它们。 现在,在陷入困境之前,我已经做到了以下几点:

countylist = ['01001','01002','01003','01004']
for item in countylist:

# Local variables...
file_1 = "F:\\file1.shp"
file_2 = "F:\\fileCOUNTYLIST.shp"
output_2 = "F:\\outputCOUNTYLIST.shp"

基本上,我需要将这些项放在我编写COUNTYLIST的地方(因此程序将调用“F:\file01001.shp”、“F:\file01002.shp”等)。我在网上找不到答案。我该怎么做?在

非常感谢!在


Tags: in脚本数据库foroutputlocalvariablesitem
3条回答
countylist = ['01001','01002','01003','01004']
file_1 = "F:\\file1.shp"
for item in countylist:
    file_2 = "F:\\file%s.shp" % item
    output_2 = "F:\\output%s.shp" % item
    # Here, I do my commands that are dependent on
    # the name of the file changing.

# Here, outside of the loop, file_2 and output_2 have the last
# value assigned to them.

简单的串联可以:

for item in countylist:
   file_2 = 'F:\\file' + item + '.shp'
   output_2 = 'F:\\output' + item + '.shp'

还没有人使用过这种变体,字符串的format method如何。。。在

countylist = ['01001','01002','01003','01004']
for item in countylist:
  file_1 = "F:\\file1.shp"
  file_2 = "F:\\file{0}.shp".format(item)
  output_2 = "F:\\output{0}.shp".format(item)

这种样式更灵活,因为您不仅可以使用带编号的参数,还可以使用关键字

^{pr2}$

在手册中,“这个字符串格式的方法是Python3.0的新标准,应该优先于在新代码中的字符串格式化操作中描述的%formatting。”所以知道这一点很好。在

重要提示:我认为这种方法只在Python2.6及更高版本中可用!在

相关问题 更多 >

    热门问题