0

我有 2 个字典的列表

foobar = [ {dict1},
        {dict2}
      ]

Django 的文档说 slice 模板标签的工作方式与 python slice 完全一样。

所以我在 python shell 中进行了测试,果然:

>>> foo = [1,2]
>>> foo[-2]
1

但是,当我在模板中执行此操作时:

{% with foobar|slice:"-2" as previous_thing %}
{{ previous_thing }}

我得到一个空列表[]

{% with foobar|slice:"1" as previous_thing %}产生我所期望的(列表中的第一项),就像{{ foobar }}(2个字典的列表)一样。

到底他妈发生了什么?!

4

1 回答 1

3
>>> foo = [1,2]

这称为索引:

>>> foo[-2]
1

这称为切片:

>>> foo[:-2]  #return all items up to -2 index(i.e 0th index), so empty list
[]
>>> foo[:-1]
[1]
>>> foo[:2]
[1, 2]

切片也适用于不存在的索引:

>>> foo[-10000:100000]
[1, 2]

但索引不会:

>>> foo[100000]
Traceback (most recent call last):
    foo[100000]
IndexError: list index out of range
于 2013-09-06T18:00:08.493 回答