簡體   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