AnsweredAssumed Answered

Counting consecutive numbers in a list

Question asked by jasonwilder on Mar 22, 2019
Latest reply on Mar 22, 2019 by jasonwilder

Table Mock-Up

Hi there. I need help assembling a python script that counts the number of consecutive numbers in a Field (Long Int) and writes that count in another field for those numbers. The field comes sorted appropriately.The image is what I am trying to accomplish. I cobbled together an Update Cursor, but having a hard time integrating the counting code into it. Any help is much appreciated.

 

import arcpy

fc = r'C:\Users\a19573\Desktop\Test\Test.gdb\TestCount'
fields = ['Consecutive','Count']

count_values = {}

with arcpy.da.UpdateCursor (fc, fields) as cursor:
    for row in cursor:
        if not row[0] in count_values.keys():
            count_values[row[0]] = 1
        else:
            count_values[row[0]] += 1
        row[1] = count_values[row[0]]
        cursor.updateRow(row)

### Test Code to integrate into Update Cursor above
random_list=[1,4,5,6,7,9,9,19,21,22,23,24] # Set of consecutive numbers in Field 'Consecutive'
def count_consec(lst):
    consec = [1]
    for x, y in zip(lst, lst[1:]):
        if x == y - 1:
            consec[-1] += 1
        else:
            consec.append(1)
    return consec
print(count_consec(random_list))

Outcomes