简体   繁体   中英

ArcGIS Field Calculator: Conditional statement syntax error

Rudimentary Python/ArcPy skills at work here, not sure where I'm going wrong.

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. 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. NewID is an attribute containing FID's values. 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. If I replace !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!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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