4

I'm working with python 2.7 (quite a beginner). I have a list, and I have a feature class with :

A = a field that contains values that I would like to use as the start of the slicing

B= a field that contains values indicating the number of items I need to take into my slicing.

Actually, I would like to do something like this :

list = [1,2,3,4,5,6,7,8,9,10,11,12]

rows = ap.SearchCursor(fc, fields = "A; B")

for row in rows:

    a = row.getValue("A")

    b = row.getValue ("B")

    newlist= list[a: (a+b)]

But its not working, I got an error "slice indices must be integers or None or have an index method"

  • 1
    I am pretty new to python too so i can't help with the code but the error message sounds like the field has the wrong format (text?) check that and try int(A) – Papierwolf Feb 19 '16 at 16:18
  • 1
    Before using ArcPy, you need to learn Python: Explain Python's slice notation – gene Feb 19 '16 at 16:24
  • Could you please provide an example of your intended output? – Aaron Feb 19 '16 at 16:26
  • 1
    a,b and a+b needs to be integers in the range of len(numList) = 12. You can try with int(a) and int(b) – gene Feb 19 '16 at 16:46
  • 1
    @Aaron : my list contains actually julian days (from Mars to end of June) , my "A" field contains a julian day that corresponds to a visit day (of a nest) and my field "B" contains the number of days since the last visit. I want to use the "newlist" to calculate the average of weather conditions during that lapse of time. – Pascale R. Feb 19 '16 at 16:50
4

Here is the working code for what you showed in the question. However, keep in mind that everything is zero indexed, so if you want to start at the true numbered item in the list you need to reference a-1 instead of a.

import arcpy

fc = r'C:\YourGDB.gdb\YourFC'

numList = [1,2,3,4,5,6,7,8,9,10,11,12]

with arcpy.da.SearchCursor(fc, ("A", "B")) as cursor:
    for row in cursor:
        a = int(row[0])
        b = int(row[1])
        newList = numList[a:(a+b)]
        print newList
        print " "

If you need to account for zero indexing:

newList = numList[(a-1):((a-1)+b)]

Not the answer you're looking for? Browse other questions tagged or ask your own question.