遍历列表或元组?

2024-10-04 05:25:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些坐标存储在列表中。我在迭代列表,我想把坐标写在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文件?所谓的“正确”坐标,就像我的第一个例子

谢谢


Tags: 文件代码http列表wwwopenkmlnum
3条回答

不知道为什么要将输入字符串转换为浮点值,只是为了能再次将它们转换为字符串。这里有一个单行线来获取这些字符串的列表:

['<coordinates>-{}, {}</coordinates>'.format(*pair) for pair in zip(oneLong, oneLat)]

分解它。。。在

zip()返回(long,lat)对的元组。在

[]理解使用zip,为左手部分创建一个元素。在

左侧部分使用format()函数用字符串填充模板。在

*对展开从zip()返回的元组,因此该元组的每个成员都被视为一个单独的参数。如果你不喜欢这种理解方式,你可以更明确地说:

^{pr2}$

如果你有很多这样的东西,最好用parens替换[list comprehension],这只会使它成为一个迭代器,所以你不必创建一个中间列表。然后你可以做点什么:

lines = ('<coordinates>-{}, {}</coordinates>\n'.format(*pair) for pair in zip(longIter, latIter))
with open('yourFile', 'w') as file:
    for line in lines:
        file.write(line)

长的和长的可以是列表,或者其他形式的iterable。在

问题出在你的break行上。只在第一次迭代之后就脱离了coordPair循环。您的while循环运行len(coordPairs)==3次,因此第一项重复3次。在

以下是一些改进的代码(注释):

oneLat = ['53.8041778', '59.8149016457', '51.1289412359']
oneLong = ['1.5192528', '1.57945488999', '8.57262235411']

# Do the negation here, instead of in the string formatting later
coordPairs = zip((-float(x) for x in oneLong), (float(x) for x in oneLat))

with open("file",'w') as f:
    f.write(xmlHeaderStuff) # I've left out your string literal for brevity    

    #I assume the purpose of the two loops, the while loop and for loop,
    #is for the purpose of repeating the group of 3 coord pairs each time?

    for i in range(len(coordPairs)):
        for coord in coordPairs:
            f.write("\t\t<coordinates>{}, {}</coordinates>\n".format(*coord))
            # break <  this needs to go

    f.write(xmlFooterStuff)

# f.close() <  this is unnecessary, since the `with` block takes care of
# file closing automatically

你为什么要把事情搞得这么复杂?您引入了一些奇怪的num迭代计数器,但根本没有使用它。我不想调试你的代码,因为它太臃肿了,但给你一些工作。在

您可以简单地迭代zip对象,如下所示:

oneLat = ['53.8041778', '59.8149016457', '51.1289412359']
oneLong = ['1.5192528', '1.57945488999', '8.57262235411']


coord_pairs = zip(oneLong, oneLat)
for coord in coord_pairs:
    print( "{}, {}".format(coord[0], coord[1]) )

输出看起来不错:

^{pr2}$

我想你应该可以把它写回文件里。在

编辑:好吧,我知道出了什么问题。这虽然在coord_pairs上迭代了3次,但循环中有break,因此它在coord_pairs的第一个元素处停止。这就是为什么第一对重复3次。抱歉,坦率地说,代码看起来像是受影响的编码。在

相关问题 更多 >