Search code examples
pythonarcpy

Swap strings in list into ints (Python)


I'm trying to use arcpy to add a list of coordinates into shapefile, I'm using this code:

with open("pathtomyfile") as f1:
    for line in f1:
        str = line.split()
        mylist.append(str)
fc = "pathtomyshapefile"
cursor = arcpy.da.InsertCursor(fc, ["SHAPE@XY"])
for row in mylist:
    cursor.insertRow(row)
del cursor

However I'm encountering an error:

TypeError: sequence size must match size of the row

I've realised that this is caused by my list looking like:

[['1.222', '3.3333'],['333.444', '4444.5555']]

Instead of

[[1.222, 3.3333],[3.4444, 4.55555]]

Yet I have no clue how to fix it. Any help?


Solution

  • So if you have the list:

    l = [['1.222', '3.3333'],['333.444', '4444.5555']]
    

    then what you are trying to do is convert each element to a float, this can be done with:

    [[float(i) for i in j] for j in l]
    

    which outputs a new list with contents:

    [[1.222, 3.3333], [333.444, 4444.5555]]
    

    Upon further inspection, it seems you may actually want the output of:

    [[1.222, 3.3333],[3.4444, 4.55555]]
    

    in this case, you can simply do:

    [[float(i[i.index('.')-1:]) for i in j] for j in l]
    

    or alternatively:

    [[float(i) % 10 for i in j] for j in l]
    

    but this second option leads to slightly off floats due to how Python handles them:

    [[1.222, 3.3333], [3.444000000000017, 4.555500000000393]]