按列组织表数据

时间:2014-01-14 17:21:02

标签: python html css django

我有一个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>

2 个答案:

答案 0 :(得分:3)

在您的上下文中使用izip_longest定义records以压缩两个列表。

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/

答案 1 :(得分:0)

以下是完整的答案: 首先,让我们修复上下文:

if len(a) <= len(b):
    a += ['-', ] * (len(b) - len(a))
else:
    b += ['-', ] * (len(a) - len(b))

my_composite_list = zip(a, b)

编辑: - 您可以使用itertools -

my_composite_list = izip_longest(a, b)

我们将其传递给上下文。

然后,在模板中:

<table>
    <thead>
        <tr>
            <th>List A</th>
            <th>List B</th>
        </tr>
    </thead>
    <tbody>
        {% for a, b in my_composite_list %}
            <tr>
                 <td>{{ a }}</td><td>{{ b }}</td>
            </tr>              
        {% endfor %}
    </tbody>
</table>
相关问题