2014-10-07 99 views
0

我有兩個關於結合列表的問題 請指導我謝謝。蟒蛇結合列表與訂單

這裏是我的代碼:

product['image_urls'] = [ 
    "http://A.jpg", 
    "http://B.jpg", 
    "http://C.jpg" ] 

product['image'] = [{ 
     "url" : "http://A.jpg", 
     "path" : "full/1.jpg", 
     "checksum" : "cc76"}, 
    { 
     "url" : "http://B.jpg", 
     "path" : "full/2.jpg", 
     "checksum" : "2862"}, 
    { 
     "url" : "http://C.jpg", 
     "path" : "full/3.jpg", 
     "checksum" : "6982"}] 

而我寫這篇文章:

for url in product['image_urls']: 
    for info in product['image']: 
     print url,info['url'],info['path'],info['checksum'] 

結果是:

http://A.jpg http://A.jpg full/1.jpg cc76 
http://A.jpg http://B.jpg full/2.jpg 2862 
http://A.jpg http://C.jpg full/3.jpg 6982 
http://B.jpg http://A.jpg full/1.jpg cc76 
http://B.jpg http://B.jpg full/2.jpg 2862 
http://B.jpg http://C.jpg full/3.jpg 6982 
http://C.jpg http://A.jpg full/1.jpg cc76 
http://C.jpg http://B.jpg full/2.jpg 2862 
http://C.jpg http://C.jpg full/3.jpg 6982 

但我想這是

http://A.jpg http://A.jpg full/1.jpg cc76  
http://B.jpg http://B.jpg full/2.jpg 2862  
http://C.jpg http://C.jpg full/3.jpg 6982 

因爲我想存儲到db像Image.objects.create(article=id,image_urls=url,url=info['url'],path=info['path'],checksum=info['checksum'])

我怎樣才能將它們結合起來?

而我的第二個問題是,你可以看到product['image_urls']product['image']['url']是一樣的。
但有時product['image']將有空值一樣(因爲它捕捉圖像時失敗):

product['image_urls'] = [ 
    "http://A.jpg", 
    "http://B.jpg", 
    "http://C.jpg" ] 

product['image'] = [{ 
     "url" : "http://A.jpg", 
     "path" : "full/1.jpg", 
     "checksum" : "cc76"}, 
     { 
     "url" : "http://C.jpg", 
     "path" : "full/3.jpg", 
     "checksum" : "6982"}] 

所以,如果我只是壓縮他們,它將錯誤的數據保存到這樣的數據庫,因爲"url" : "http://B.jpg",丟失:

[('http://A.jpg', {'url': 'http://A.jpg', 'path': 'full/1.jpg', 'checksum': 'cc76'}), ('http://B.jpg', {'url': 'http://C.jpg', 'path': 'full/3.jpg', 'checksum': '6982'})] 

請教我如何將它們結合起來?
謝謝很多

+0

你要什麼輸出看起來像在最後的例子嗎? – 2014-10-07 02:40:43

回答

0

對於每個項目在第一個列表,你想,如果在第二個列表中的相應項目的存在是爲了只打印。

我們建立了一個臨時的字典,從第一個列表中的項目鍵入,並諮詢其打印時:

# "images" will contain exactly the same info as "product['image']", but 
# keyed by the URL. 
images = { d['url']:d for d in product['image'] } 

# Print every line implied by the first data set 
for url in product['image_urls']: 
    # But only if the data is actually in the second data set 
    if url in images: 
     image = images[url] 
     print url, image['url'], image['path'], image['checksum'] 
     # Or ... 
     # Image.objects.create(article=id, 
     #      image_urls=url, 
     #      url=image['url'], 
     #      path=image['path'], 
     #      checksum=image['checksum']) 
     # Or fancier, 
     # Image.objects.create(article=id, images_urls=url, **image) 
+0

這真棒。謝謝你,我學習了一項新技能! – user2492364 2014-10-07 02:48:57