I want to define the values of first row in a sorted table with search cursor. My code is working without sorting, but I don't know how can I integrate into sorting. I would like to see only the values of first row ("src_ORIG_FID","nbr_ORIG_FID"), with the smallest area and longer length. I want to sort rows first by "src_Shape_Area" Ascending, then by LENGTH Descending. After sorting, if the "if statement" is done, the first good row is needed.
with arcpy.da.SearchCursor(tablaL,["src_ORIG_FID","nbr_ORIG_FID","src_Shape_Area","LENGTH","SUM"],"","","src_Shape_Area A;LENGTH D") as nCursor:
for row in nCursor:
if row [4]<50000.00 and row[3]> 0: #if it is TRUE
for row in nCursor:
orig1 = row[0] #only first row value is needed
orig2 = row[1]
break
else:
break
1 Answer 1
If you only have ~100 rows you can list all values, and then sort using python:
import arcpy
fc = r'C:\GIS\ArcMap_default_folder\Default.gdb\my_sample'
fields = ['OBJECTID', 'KKOD', 'Shape_Length', 'Shape_Area']
data = [row for row in arcpy.da.SearchCursor(fc, fields) if row[2]>0 and row[3]<50000] #List all rows meeting the if conditions
data.sort(key=lambda x: (x[2], -x[3])) #Sort by field index 2 and 3 (-3 for descending sort)
orig1, orig2 = data[0][:2] #Fetch first and second value of the first row in the sorted list of tuples
sql_clause
is a two-element list). It also includes the textNote: DISTINCT, ORDER BY, and ALL are only supported when working with databases.