python将列表与顺序相结合
关于合并列表,我有两个问题 请引导我,谢谢 这是我的密码:python将列表与顺序相结合,python,Python,关于合并列表,我有两个问题 请引导我,谢谢 这是我的密码: product['image_urls'] = [ "http://A.jpg", "http://B.jpg", "http://C.jpg" ] product['image'] = [{ "url" : "http://A.jpg", "path" : "full/1.jpg", "checksum" : "cc76"}, { "u
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.createarticle=id,Image\u url=url,url=info['url'],path=info['path'],checksum=info['checksum']
我怎样才能把它们结合起来呢
我的第二个问题是,你可以看到产品['image\u url'],而产品['image']['url']是相同的。
但有时产品['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)
在最后一个示例中,您希望输出是什么样的?