简体   繁体   English

ArcGIS Field Calculator:条件语句语法错误

[英]ArcGIS Field Calculator: Conditional statement syntax error

Rudimentary Python/ArcPy skills at work here, not sure where I'm going wrong. 基本的Python / ArcPy技能在这里起作用,不确定我哪里出错了。

Trying to do a simple random selection of 10 features from a layer to be indicated by the placement of a "1" in another attribute set aside for this purpose. 尝试从一个图层中随机选择10个要素,以在为此目的预留的另一个属性中放置“ 1”来表示。 Basic concept is is to use random.sample() to generate a random list of 10 FID's, and then check to see if each FID is in the list. 基本概念是使用random.sample()生成10个FID的随机列表,然后检查列表中是否包含每个FID。 NewID is an attribute containing FID's values. NewID是包含FID值的属性。 This is what I have in the code block: 这是我在代码块中的内容:

import random
def randSelTen():
      featurecount = arcpy.GetCount_management("layer_name")
      linecount = int(str(featurecount))
      lst_oids = range(0, linecount)
      rand_lines = random.sample(lst_oids, 10)
      if !NewID! in rand_lines:
           return 1
      else:
           return 0

I keep getting a syntax error on the conditional containing !NewID!, and no matter what I do I can't fix it. 我不断收到包含!NewID!的条件的语法错误,并且无论如何我都无法修复它。 If I replace !NewID! 如果我替换!NewID! with an integer, the script runs, but of course the output is bad. 如果使用整数,脚本将运行,但是输出当然不好。 Any help is appreciated... thanks! 任何帮助表示赞赏...谢谢!

If you are putting this code in the "Codeblock" of the field calculator then the reason you are getting a syntax error is because you can not access fields like that from the codeblock. 如果将这段代码放在字段计算器的“代码块”中,那么得到语法错误的原因是因为您无法从代码块访问类似的字段。 You must pass in the field as an argument to the function. 您必须将字段作为函数的参数传递。 So you would have to do this: 因此,您必须这样做:

# -----Codeblock---------
import random
def randSelTen(NewID):
  featurecount = arcpy.GetCount_management("layer_name")
  linecount = int(str(featurecount))
  lst_oids = range(0, linecount)
  rand_lines = random.sample(lst_oids, 10)
  if NewID in rand_lines:
       return 1
  else:
       return 0

# ----- Expression (goes in bottom text box of the field calculator if using GUI) -----
randSelTen(!NewID!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM