Django 数组或列表输出?
我正在提取一组图像网址及其各自的标题。我尝试创建哈希或关联数组,但数据似乎会被覆盖,因此我最终只得到数组中的最后一项。
例如;
thumbnail_list = []
for file in media:
thumbnail_list['url'] = file.url
thumbnail_list['title'] = file.title
我什至尝试创建两个列表并将它们放入一个更大的列表中。
thumbnail_list.append('foo')
thumbnail_urls.append('bar')
all_thumbs = [thumbnail_list], [thumbnail_urls]
我正在尝试从这些数据中创建一个链接:
<a href="image-url">image title</a>
我一直在接近,但最终我在 django 模板中一次循环了太多数据或所有数据。
有想法吗?
编辑:也许 zip() 是我需要的?
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print 'What is your {0}? It is {1}.'.format(q, a)
I'm pulling a set of image urls and their respective titles. I've tried creating a hash or associative array, but the data seems to overwrite so I only end up with the last item in the array.
For example;
thumbnail_list = []
for file in media:
thumbnail_list['url'] = file.url
thumbnail_list['title'] = file.title
I've even tried creating two lists and putting them in a larger one.
thumbnail_list.append('foo')
thumbnail_urls.append('bar')
all_thumbs = [thumbnail_list], [thumbnail_urls]
I'm trying to create a link out of this data:
<a href="image-url">image title</a>
I keep getting close, but I end up looping over too much data or all of the data at once in my django template.
Ideas?
Edit: Maybe zip() is what I need?
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print 'What is your {0}? It is {1}.'.format(q, a)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你想要一个 dict,这是 Python 的关联数据结构,而你正在创建一个列表。
但我不确定我是否理解你的问题。为什么不直接将您的
media
集合传递到模板中并像这样迭代:编辑
根据您的评论,我现在假设您正在寻找这样的东西:
您可以创建一个列表,然后对于每个文件,在处理完 URL、标题或其他内容后,将字典附加到该列表中。
或者,您可以创建自己的类来更好地封装它,以防您有其他逻辑要应用:
You want a dict, which is Python's associative data structure, whereas you are creating a list.
But I'm not sure I understand your problem. Why not just pass your
media
collection into the template and iterate like this:EDIT
Based on your comment, I now presume you are looking for something like this:
You can create a list, then for each file, append a dictionary into that list after you've processed the URL, title, or whatever.
Or, you could create your own class that encapsulates this a little better in case you have other logic to apply: