gpt4 book ai didi

python - 按列组织表格数据

转载 作者:行者123 更新时间:2023-11-30 23:29:33 25 4
gpt4 key购买 nike

我有一个 django 模板,它传递两个不同大小的列表(但每个列表至少有一个元素)。我试图在表格中显示这些数据,使其看起来像这样:

List A | List B
-------------------
A - 1 | B - 1
A - 2 | B - 2
A - 3 |
A - 4 |

(B 中的空单元格可以是空的,或者类似“--”的内容)

我不知道该怎么做。我错过了一些明显的东西吗?

(注意:我不是那个想要将其作为表格的人;我将它作为两个不错的列表,它看起来很完美,但我被否决了 - 我被一张表格困住了。)

编辑:
所以我用 django for 循环迭代每个列表。我正在寻找这样的东西:

<table>
<tr>
<th>List A</th>
<th>List B</th>
</tr>

#first column
{% for person in listA %}
<td>person</td>
{% endfor %}

#second column

{% for person in listB %}
<td>person</td>
{% endfor %}
</table>

最佳答案

在您的上下文中使用 izip_longest 定义记录来压缩两个列表。

from itertools import izip_longest

listA = [1, 2, 3, 4]
listB = [1, 2, '--']

records = izip_longest(listA, listB)
# will return [(1, 1), (2, 2), (3, '--'), (4, None)]

稍后在您的模板上执行此操作。

<table>
<tr>
<th>Col1</th>
<th>Col2</th>
<tr>
{% for col1, col2 in records %}
<tr>
<td>{{col1}}</td>
<td>{{col2}}</td>
<tr>
{% endfor %}
</table>

在这里查看它的工作http://djangotemplator.appspot.com/t/68342edf5d964872a0743a6a6183ef56/

关于python - 按列组织表格数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21119812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com