繁体   English   中英

遍历列表或元组?

[英]Iterating through a list or tuple?

我已经将一些坐标存储为列表。 我正在遍历列表,我想将坐标写入KML文件中。 因此,我应该得到类似以下内容的结果:

<coordinates>-1.59277777778, 53.8271055556</coordinates>
<coordinates>-1.57945488999, 59.8149016457</coordinates>
<coordinates>-8.57262235411, 51.1289412359</coordinates>

我遇到的问题是我的代码导致列表中的第一项重复了三遍:

 <coordinates>-1.59277777778, 53.8271055556</coordinates>
 <coordinates>-1.59277777778, 53.8271055556</coordinates>
 <coordinates>-1.59277777778, 53.8271055556</coordinates>

我想我知道为什么会这样,因为脚本看到了.strip行,并打印了列表中的第一项3次。

这是我的代码:

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文件? 我所说的“正确”坐标就像第一个例子

谢谢

问题出在您的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]) )

Ouput看起来不错:

1.5192528, 53.8041778
1.57945488999, 59.8149016457
8.57262235411, 51.1289412359

我认为您应该可以将其写回文件中。

编辑:好的,我知道出了什么问题。 这虽然在coord_pairs迭代了3次,但是循环在内部break ,所以它在coord_pairs第一个元素处coord_pairs 这就是第一对重复3次的原因。 坦率地说很抱歉,但是代码看起来像是“影响力下的编码”。

不确定为什么要将输入字符串转换为浮点数,只是为了再次将它们转换为字符串。 这是一个获取这些字符串列表的衬里:

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

分解...

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

对[]的理解会消耗zip,为左手部分创建一个元素。

左手部分使用format()函数用您的字符串填充模板。

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

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

如果您有很多这样的方法,最好用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)

longIter和latIter可以是列表或其他形式的可迭代对象。

暂无
暂无

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

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