简体   繁体   中英

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?

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM