2014-10-07 105 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