我有一些坐标存储在列表中。我在迭代列表,我想把坐标写在KML文件中。因此,我应该以类似于以下内容的方式结束:
<coordinates>-1.59277777778, 53.8271055556</coordinates>
<coordinates>-1.57945488999, 59.8149016457</coordinates>
<coordinates>-8.57262235411, 51.1289412359</coordinates>
我遇到的问题是,我的代码会导致列表中的第一项重复三次:
^{2}$我想我知道为什么会发生这种情况,因为脚本会看到.strip行并将列表中的第一项打印三次。在
这是我的代码:
oneLat = ['53.8041778', '59.8149016457', '51.1289412359']
oneLong = ['1.5192528', '1.57945488999', '8.57262235411']
with open("file",'w') as f:
f.write('''<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
<name>TracePlace</name>
<open>1</open>
<Style id="Photo">
<IconStyle>
<Icon>
<href>../pics/icon.jpg</href>
</Icon>
</IconStyle>
<LineStyle>
<width>0.75</width>
</LineStyle>
</Style>
<Folder>''')
coord_pairs = zip(map(float, oneLong), map(float, oneLat))
itemsInListOne = int(len(oneLat))
iterations = itemsInListOne
num = 0
while num < iterations:
num = num + 1
for coord in coord_pairs:
print (str(coord).strip('()'))
f.write("\t\t<coordinates>" + "-" + (str(coord).strip('()')) + "</coordinates>\n")
break
f.write('''
</Folder>
</Document>
</kml>''')
f.close()
如何获得正确的“映射”坐标以写入KML文件?所谓的“正确”坐标,就像我的第一个例子
谢谢
不知道为什么要将输入字符串转换为浮点值,只是为了能再次将它们转换为字符串。这里有一个单行线来获取这些字符串的列表:
分解它。。。在
zip()返回(long,lat)对的元组。在
[]理解使用zip,为左手部分创建一个元素。在
左侧部分使用format()函数用字符串填充模板。在
*对展开从
^{pr2}$zip()
返回的元组,因此该元组的每个成员都被视为一个单独的参数。如果你不喜欢这种理解方式,你可以更明确地说:如果你有很多这样的东西,最好用parens替换[list comprehension],这只会使它成为一个迭代器,所以你不必创建一个中间列表。然后你可以做点什么:
长的和长的可以是列表,或者其他形式的iterable。在
问题出在你的
break
行上。只在第一次迭代之后就脱离了coordPair
循环。您的while
循环运行len(coordPairs)==3
次,因此第一项重复3次。在以下是一些改进的代码(注释):
你为什么要把事情搞得这么复杂?您引入了一些奇怪的
num
迭代计数器,但根本没有使用它。我不想调试你的代码,因为它太臃肿了,但给你一些工作。在您可以简单地迭代
zip
对象,如下所示:输出看起来不错:
^{pr2}$我想你应该可以把它写回文件里。在
编辑:好吧,我知道出了什么问题。这虽然在
coord_pairs
上迭代了3次,但循环中有break
,因此它在coord_pairs
的第一个元素处停止。这就是为什么第一对重复3次。抱歉,坦率地说,代码看起来像是受影响的编码。在相关问题 更多 >
编程相关推荐