【问题标题】:Django Partition Filter SnippetDjango 分区过滤器片段
【发布时间】:2014-05-14 13:03:21
【问题描述】:

我正在使用其中一个分区 Django sn-ps 将数据拆分为 3 列,当一切正常时,我不知道如何调用中间分区。

片段

@register.filter
def partition(thelist, n):
try:
    n = int(n)
    thelist = list(thelist)
except (ValueError, TypeError):
    return [thelist]
p = len(thelist) / n
return [thelist[p*i:p*(i+1)] for i in range(n - 1)] + [thelist[p*(i+1):]]

模板

{% for x in y|partition:"3"|first %} (working, shows first 1/3)
{% for x in y|partition:"3"|middle %} (not working)
{% for x in y|partition:"3"|last %} (working, shows last 1/3)

显然“中间”是不正确的。我尝试了“第二个”,它也没有工作。

有什么建议吗?

【问题讨论】:

    标签: python django code-snippets


    【解决方案1】:

    firstlast 是模板过滤器,用于获取列表的第一个和最后一个元素。没有模板过滤器来获取第二个、第三个等元素。您必须使用 for item in .. 构造:

    {% for row in mylist|partition:"3" %}
        {% for item in row %}
            do something with {{ item }}
        {% endfor %}
    {% endfor %}
    

    【讨论】:

    • 感谢您的反馈。虽然您的代码正在运行,但它并不是我想要的,因为我的目标是将数据分成三份,上面显示所有数据 3 倍。有什么建议可以将数据分成三等份吗?
    猜你喜欢
    • 2018-05-11
    • 1970-01-01
    • 2018-02-22
    • 2019-08-17
    • 2010-12-15
    • 1970-01-01
    • 2020-03-20
    • 2017-01-31
    • 2016-05-01
    相关资源
    最近更新 更多