迭代数组并将字符串作为属性名应用的正确方法?

2024-03-29 10:26:05 发布

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

我有一个包含大量列和行的.csv文件。我使用python读取csv并在ArcGIS中创建一个表/要素类,然后用.csv中的行填充该表。我正在寻找以下方面的最佳方式/速记方法:

我有一个代表.csv“csv\u头”第一行的列表

下面是一个简短的CSV示例,该列表如下所示:

csv_headings = ['Key', 'X', 'Y', 'Value1', 'Value2'...]

Key        X      Y       Value1    Value2    ...
2221    192934  875767     96.4      95.4
2222    194459  834763     96.3      99.9
2223    193934  905606     90.6      95.1
2224    191974  855100     91.0      95.2
...

目前,以下内容用于填充ArcGIS中的表/要素类:

with open("C:\\path_to_csv.csv", 'rb') as f:
  reader = csv.DictReader(f)
  for row in reader:
    # Create the feature
    feature = cursor.newRow()

    # Add the point geometry to the feature
    vertex = arcpy.CreateObject("Point")
    vertex.X = row['X']
    vertex.Y = row['Y']
    feature.shape = vertex

    # Add attributes
    feature.Key = row['Key']
    feature.X = row['X']
    feature.Y = row['Y']
    feature.Value1 = row['Value1']
    feature.Value2 = row['Value2']

我的完整数据集有43列,目前全部以“feature.ValueX=row['ValueX']的形式手动写入43行,我希望缩短这些行

基本上,我希望将“csv_头”循环为x,并将x应用为属性名和行标题,假设:

    # Add attributes

    for x in csv_headers:
      feature.x = row[x]

然而,这将不起作用,只是想知道什么是正确的思维方式,这可能是?任何帮助将不胜感激