2014-07-05 56 views
0

我正在用Python弄溼我的腳。我從來沒有做過任何編程或從未做過什麼,我真的很感激,如果有人會解釋his_hers的答案,而不是隻發佈它,因爲我想學習一些東西!更好的是不發佈answere,但只是提示我應該看什麼或什麼:)將列表中的值插入到字符串中python

我有很多價值觀(數字)一個一方的列表。 另一方面,我有一個URL需要通過多個列表中的數字進行更新,然後將其保存到另一個列表中以便進一步處理。

#borders of the bbox 
longmax = 15.418483 #longitude top right 
longmin = 4.953142 #longitude top left 
latmax = 54.869808 #latitude top 
latmin = 47.236219 #latitude bottom 

#longitude 
longstep = longmax - longmin 
longstepx = longstep/100 #longitudal steps the model shall perfom 


#latitude 
latstep = latmax - longmin 
latstepx = latstep/100 #latitudal steps the model shall perform 


#create list of steps through coordinates longitude 
llong = [] 
while longmin < longmax: 
    longmin+=longstepx 
    llong.append(+longmin) 


#create list of steps through coordinates latitude 
llat = [] 
while latmin < latmax: 
    latmin+=latstepx 
    llat.append(+latmin) 


#create the URLs and store in list 
for i in (llong): 
    "https://api.flickr.com/services/rest/?method=flickr.photos.search&format=json&api_key=5....lback=1&page=X&per_page=500&bbox=i&accuracy=1&has_geo=1&extras=geo,tags,views,description",sep="")" 

正如您所看到的,我嘗試從flickr向REST API發出請求。 我不明白的是:

  1. 我怎麼循環都要經過我的列表,插入從列表中值在URL中的某一點?
  2. 如何告訴循環在將第一個數字從列表「llong」和「llat」中插入之後單獨保存每個URL,然後繼續處理下兩個數字。

任何提示?

回答

0

您可以使用string formatting插入任何你想進入你的網址:

my_list=["foo","bar","foobar"] 

for word in my_list: 
    print ("www.google.com/{}".format(word)) 
www.google.com/foo 
www.google.com/bar 
www.google.com/foobar 

{}在字符串中使用,無論你想插入。

要將它們保存到列表中,您可以使用zip,使用字符串格式化插入,然後追加到新列表。

urls=[] 
for lat,lon in zip(llat,llong): 
    urls.append("www.google.com/{}{}".format(lat,lon)) 

Python string formatting: % vs. .format

我認爲.format()方法是相對於使用的"www.google.com/%s" % lat語法的優選方法。 有回答here討論一些差異。

拉鍊功能最好用一個例子來解釋:

說我們有2所列出L1和L2:

l1 = [1,2,3] 
l2 = [4,5,6] 

如果我們使用zip(l1,l2)結果將是:

[(1, 4), (2, 5), (3, 6)] 

然後,當我們循環兩個壓縮列表,如下所示:

for ele_1,ele_2 in zip(l1,l2): 
    first iteration ele_1 = 1, ele_2 = 4 
    second iteration ele_1 = 2 ele_2 = 5 and so on ... 
+0

你已經打敗了我的答案。您還可以添加「打印」www.google.com/%s「%word」嗎?並在'urls.append(「www.google.com/%f%f」%(lat,lon))''上做同樣的事情?這將使您的答案更全面,從而爲OP提供更多的知識和選擇。 – alvits

+1

@alvits我認爲字符串格式是首選的方法,我會添加一個鏈接到一個討論差異的SO問題。 –

+0

太棒了。我學到了很多!謝謝Padraic! – Stophface

0
myUrls=[] 
for i in range len(llat) # len(llong) is valid if both have same size. 
    myUrls.append(newUrl(llat[i]),llong[i]) 


def newUrl(lat,long): 
    return "www.flickr.......lat="+lat+".....long="+long+"...." 
+1

請解釋**爲什麼這個代碼的工作是阻止複製和粘貼代碼。 OP應該理解你的選擇背後的分歧,以便讓他/她最終決定這段代碼是否最終是他/她想要使用的代碼。 – rayryeng

相關問題