![](/img/trans.png)
[英]Combine numerous lists of different length in python in an alternating order
[英]python combine lists with order
關於合並列表,我有兩個問題,請指導我謝謝。
這是我的代碼:
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
因為我想像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'})]
請教我如何結合它們??
非常感謝
對於第一個列表中的每個項目,僅當第二個列表中的相應項目存在時才要打印。
我們建立一個臨時字典,以第一個列表中的項目為關鍵字,並在打印時進行參考:
# "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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.