将列表中的字符串交换为整数 (Python)
Swap strings in list into ints (Python)
我正在尝试使用 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
但是我遇到了一个错误:
TypeError: sequence size must match size of the row
我意识到这是由我的列表造成的:
[['1.222', '3.3333'],['333.444', '4444.5555']]
而不是
[[1.222, 3.3333],[3.4444, 4.55555]]
但我不知道如何修复它。有帮助吗?
所以如果你有 list
:
l = [['1.222', '3.3333'],['333.444', '4444.5555']]
那么你要做的是将每个元素转换为 float
,这可以通过以下方式完成:
[[float(i) for i in j] for j in l]
其中 outputs
一个新的 list
内容为:
[[1.222, 3.3333], [333.444, 4444.5555]]
经进一步检查,您似乎实际上想要 output
of:
[[1.222, 3.3333],[3.4444, 4.55555]]
在这种情况下,你可以简单地做:
[[float(i[i.index('.')-1:]) for i in j] for j in l]
或者:
[[float(i) % 10 for i in j] for j in l]
但是由于 Python 处理它们的方式,第二个选项会导致稍微偏离 floats
:
[[1.222, 3.3333], [3.444000000000017, 4.555500000000393]]
我正在尝试使用 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
但是我遇到了一个错误:
TypeError: sequence size must match size of the row
我意识到这是由我的列表造成的:
[['1.222', '3.3333'],['333.444', '4444.5555']]
而不是
[[1.222, 3.3333],[3.4444, 4.55555]]
但我不知道如何修复它。有帮助吗?
所以如果你有 list
:
l = [['1.222', '3.3333'],['333.444', '4444.5555']]
那么你要做的是将每个元素转换为 float
,这可以通过以下方式完成:
[[float(i) for i in j] for j in l]
其中 outputs
一个新的 list
内容为:
[[1.222, 3.3333], [333.444, 4444.5555]]
经进一步检查,您似乎实际上想要 output
of:
[[1.222, 3.3333],[3.4444, 4.55555]]
在这种情况下,你可以简单地做:
[[float(i[i.index('.')-1:]) for i in j] for j in l]
或者:
[[float(i) % 10 for i in j] for j in l]
但是由于 Python 处理它们的方式,第二个选项会导致稍微偏离 floats
:
[[1.222, 3.3333], [3.444000000000017, 4.555500000000393]]