For loop through field values in Calculate Field tool

3607
10
02-25-2021 11:37 AM
Labels (2)
AaronWorthley1
Occasional Contributor II

Pulling my hair out here...I'm trying to rebuild a for loop in a field calculator tool in modelbuilder. No matter what I try, the for loop only returns the last value of the iteration. This should be so simple, but I've been stuck for hours! Tried all sorts of reconfigurations.

I have several fields with H,M,L or N values. Each of those should be assigned a score, which is then summed and returned for the new field. No matter what I do, the returned value is caculated ONLY based on the last field in the list as if I had the sum = 0 line inside the For loop...but I don't.

Any ideas?

CalcFVScore([!Field1!,!Field2!,!Field3!,!Field4!])

Code Block:

def CalcFVScore(fields):
    sum = 0
    for f in fields:
        if f == "H":
            score = 5
        elif f == "M":
            score = 3
        elif f == "L":
            score = 1
        else:
            score = 0
        sum = sum + score
    return sum

0 Kudos
10 Replies
DanPatterson
MVP Esteemed Contributor

 

def CalcFVScore(flds):
    sum = 0
    for f in flds:
        if "H" in f:
            sum += 5
        elif "M" in f:
            sum += 3
        elif "L" in f:
            sum += 1
        else:
            sum += 0
    return sum

 

in case there are stray things in the fields.

Try it with 2 fields first to see if it is passing the list of field names properly


... sort of retired...
0 Kudos