简体   繁体   English

将列表中的字符串交换为int(Python)

[英]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: 我正在尝试使用arcpy将坐标list添加到shapefile ,我正在使用以下代码:

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 : 因此,如果您有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 ,这可以通过以下方式完成:

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

which outputs a new list with contents: outputs包含内容的新list

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

Upon further inspection, it seems you may actually want the output of: 经过进一步检查,似乎您实际上可能需要以下output

[[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: 但是由于Python处理floats第二个选项导致floats略有下降:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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