Python 使用jinja2对Nexted列表进行迭代

Python 使用jinja2对Nexted列表进行迭代,python,list,dictionary,flask,jinja2,Python,List,Dictionary,Flask,Jinja2,我有来自烧瓶的3个列表包含“名称”“部门”“位置”,我需要创建一个表并使用所有3个列表污染行 **问题我无法一次访问所有3list数据 所以我在StackOverflow的某个地方阅读,将我的列表链接到字典,并将字典链接到列表 an_item = dict(name=names, department= departments, position=positions) itema.append(an_item) **如果名称是字符串而不是列表,则可以正常工作 烧瓶侧: names = ["Al

我有来自烧瓶的3个列表包含“名称”“部门”“位置”,我需要创建一个表并使用所有3个列表污染行

**问题我无法一次访问所有3list数据

所以我在StackOverflow的某个地方阅读,将我的列表链接到字典,并将字典链接到列表

an_item = dict(name=names, department= departments, position=positions)
itema.append(an_item)
**如果名称是字符串而不是列表,则可以正常工作

烧瓶侧:

names = ["Alice", "Mike", ...]
department = ["CS", "MATHS", ... ]
position = ["HEAD", "CR", ....]

an_item = dict(name=names, department= departments, position=positions)
itema.append(an_item)
HTML:


这是因为您不正确地构建词典。当您执行dict(name=names,department=departments,position=positions)时,这实际上只是创建了一个名称键,其值为名称列表,而department键则为部门列表。这意味着
item.name
实际上是所有名称的列表

我想你想要的是每个部门职位的字典列表。实现这一点的方法是在并行列表中循环,然后为每个索引创建一个字典并附加到列表中

names = ['joe', 'alice', 'bill']
departments = ['CS', 'Math', 'Eng']
position = ['HEAD', 'CR', 'PROF']

items = []
for i in range(len(names)):
    item = dict(name=name[i], department=departments[i], position=positions[i])
    items.append(item)

print(items) # [{'name': 'joe', 'deparment': 'CS', 'position': 'HEAD}, {'name': 'alice', 'department': 'Math',...}...]

然后在HTML中,您需要使用括号运算符或
.get()


{items%%中的项的%s}
{{item['name']}
{{item['department']}
{{item['position']}
{%endfor%}

这应该是您要查找的表。

好吧,它有点像元组,我在搜索答案时碰巧知道有一个名为zip的函数,它对循环也有类似的作用。。。我想jsonify也是一个不错的选择,你觉得呢?这里没有元组
items
是一个字典列表,每个字典代表表中的一行<在创建返回json的api端点时,最好使用code>jsonify。在这种情况下,您正在构建服务器端模板,上面列出的字典可能是您的最佳选择。
Name  Department Position
Alice CS         Head
Mike  MATHS      CR
names = ['joe', 'alice', 'bill']
departments = ['CS', 'Math', 'Eng']
position = ['HEAD', 'CR', 'PROF']

items = []
for i in range(len(names)):
    item = dict(name=name[i], department=departments[i], position=positions[i])
    items.append(item)

print(items) # [{'name': 'joe', 'deparment': 'CS', 'position': 'HEAD}, {'name': 'alice', 'department': 'Math',...}...]

<tbody>

   {% for item in items %}
   <tr>
       <td>{{item['name']}}</td>
       <td>{{item['department']}}</td>
       <td>{{item['position']}}</td>
   </tr>
   {% endfor %}
</tbody>