简体   繁体   English

遍历列表或元组?

[英]Iterating through a list or tuple?

I've got some coordinates stored as a list. 我已经将一些坐标存储为列表。 I'm iterating over the list and I want to write the coordinates in a KML file. 我正在遍历列表,我想将坐标写入KML文件中。 So I should end up with something resembling the following: 因此,我应该得到类似以下内容的结果:

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

The problem i've got is that my code results in the first item in the list being duplicated three times: 我遇到的问题是我的代码导致列表中的第一项重复了三遍:

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

I think I know why it's happening, because the script sees the .strip line and prints the first item in the list 3 times. 我想我知道为什么会这样,因为脚本看到了.strip行,并打印了列表中的第一项3次。

Here is my code: 这是我的代码:

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()

How can I get the correct 'mapped' coordinates to write to the KML file? 如何获得正确的“映射”坐标以写入KML文件? By the 'correct' coordinates, I mean like my first example 我所说的“正确”坐标就像第一个例子

Thanks 谢谢

The problem is with your break line. 问题出在您的break线上。 You break out of the coordPair loop after only the first iteration. 仅在第一次迭代后,您才退出coordPair循环。 Your while loop runs len(coordPairs)==3 times so the 1st item is repeated 3 times. 您的while循环运行len(coordPairs)==3次,因此第一个项目重复3次。

Here is your code with some improvements (annotated): 这是您的代码,其中有一些改进(带注释):

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

Why would you over complicate things so much? 你为什么要使事情变得如此复杂? You introduced some weird num iteration counter and not used it at all. 您介绍了一些奇怪的num迭代计数器,并且根本没有使用它。 I am not gonna debug your code as it feels too bloated, but give you something to work on. 我不会调试您的代码,因为它感觉太过膨胀,但是给您一些需要改进的地方。

You can simply iterate over the zip object like this: 您可以像这样简单地遍历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 seems fine: Ouput看起来不错:

1.5192528, 53.8041778
1.57945488999, 59.8149016457
8.57262235411, 51.1289412359

I think you should be able wrap it up back with writing to file. 我认为您应该可以将其写回文件中。

EDIT: OK, I figured out what was wrong. 编辑:好的,我知道出了什么问题。 This while iterated 3 times over coord_pairs , but the loop has break inside, so it stops at 1st element of coord_pairs . 这虽然在coord_pairs迭代了3次,但是循环在内部break ,所以它在coord_pairs第一个元素处coord_pairs This is why the 1st pair is repeated 3 times. 这就是第一对重复3次的原因。 Sorry to be frank but the code looks like Coding Under Influence. 坦率地说很抱歉,但是代码看起来像是“影响力下的编码”。

Not sure why you're converting your input strings to floats, just so you can turn them into strings again. 不确定为什么要将输入字符串转换为浮点数,只是为了再次将它们转换为字符串。 Here's a one liner to get a list of those strings: 这是一个获取这些字符串列表的衬里:

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

Breaking it down... 分解...

The zip() returns tuples of (long, lat) pairs. zip()返回(long,lat)对的元组。

The [ ] comprehension consumes the zip, creating an element for the left hand part. 对[]的理解会消耗zip,为左手部分创建一个元素。

The left hand part uses the format() function to fill in the template with your strings. 左手部分使用format()函数用您的字符串填充模板。

The *pair expands the the tuple that comes back from the zip() so each member of that tuple is seen as an individual argument. * pair扩展了从zip()返回的元组,因此该元组的每个成员都被视为一个单独的参数。 If you don't care for that style of comprehension, you could be more explicit: 如果您不喜欢这种理解方式,则可以更加明确:

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

If you have a lot of these, you'd be better of to replace the [list comprehension] with parens, which will just make it an iterator, so you don't have to create an intermediate list. 如果您有很多这样的方法,最好用parens代替[list comprehension],这将使其成为迭代器,因此您不必创建中间列表。 Then you could do something like: 然后,您可以执行以下操作:

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 and latIter can be lists, or other forms of iterables. longIter和latIter可以是列表或其他形式的可迭代对象。

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

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