Shu*_*Shu 5 python django hash associative-array
我正在拉一组图片网址和各自的标题.我已经尝试创建一个哈希或关联数组,但数据似乎覆盖,所以我最终只得到数组中的最后一项.
例如;
thumbnail_list = []
for file in media:
thumbnail_list['url'] = file.url
thumbnail_list['title'] = file.title
Run Code Online (Sandbox Code Playgroud)
我甚至试过创建两个列表并将它们放在一个更大的列表中.
thumbnail_list.append('foo')
thumbnail_urls.append('bar')
all_thumbs = [thumbnail_list], [thumbnail_urls]
Run Code Online (Sandbox Code Playgroud)
我正在尝试从这些数据中创建一个链接:
<a href="image-url">image title</a>
Run Code Online (Sandbox Code Playgroud)
我一直在接近,但最终我在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)
Run Code Online (Sandbox Code Playgroud)
你想要一个dict,这是Python的关联数据结构,而你正在创建一个列表.
但我不确定我理解你的问题.为什么不将你的media
集合传递给模板并迭代如下:
{% for file in media %}
<a href="{{ file.url }}">{{ file.title }}</a>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
编辑
根据你的评论,我现在假设你正在寻找这样的东西:
thumbnail_list = []
for file in media:
file_info = {}
file_info['url'] = file.url
file_info['title'] = file.title
thumbnail_list.append(file_info)
{% for file in thumbnail_list %}
<a href="{{ file.url }}">{{ file.title }}</a>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
您可以创建一个列表,然后为每个文件在处理URL,标题或其他内容后将字典附加到该列表中.
或者,您可以创建自己的类,以便在您有其他逻辑应用时更好地封装它:
class FileInfo(object):
def __init__(self, file):
self.url = file.url # do whatever
self.title = file.title # do whatever
thumbnail_list = []
for file in media:
thumbnail_list.append(FileInfo(file))
Run Code Online (Sandbox Code Playgroud)