【问题标题】:Organize table data by columns按列组织表格数据
【发布时间】:2014-01-15 01:40:02
【问题描述】:

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

【问题讨论】:

  • 不确定什么?的HTML?名单?模板语言?
  • HTML。已编辑——如果仍不清楚,请告诉我。

标签: python html css django


【解决方案1】:

在您的上下文中定义 records 使用 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/

【讨论】:

  • 太棒了!谢谢!模板也很有帮助!
【解决方案2】:

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

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>

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 2012-11-03
    相关资源
    最近更新 更多