python - 如何在 Django 中迭代数组中的所有值

标签 python arrays python-3.x django-templates

我有一个 python 名称数组,我想使用 Django 模板显示它。我知道可以使用支持循环的标签,但它们具有我不熟悉的独特语法。

而且我不想使用instance.0、instance.1等等。我需要能够针对任何大小的数组进行扩展

Django 模板代码

(:,

{% for name  in instance  %}
       {{instance}}         
{%endfor%}

 My name is {{my_name}}.
(:,

Python代码

from django.template import Template, Context
from django.conf import settings

settings.configure()


t=Template(The above section)
dtype={'names': ['name','offset'],
       'formats':['U20,U20']
       }

instance = np.zeros(5,dtype='U20')
instance[0]=('John')
instance[1]=('Tim')
instance[2]=('Sarah')

name="adrian"


c=Context({"instance":instance, "my_name":name})
print(t.render(c))

电流输出

(:,

                ['John' 'Tim' 'Sarah' '' '']


                ['John' 'Tim' 'Sarah' '' '']


                ['John' 'Tim' 'Sarah' '' '']


                ['John' 'Tim' 'Sarah' '' '']


                ['John' 'Tim' 'Sarah' '' '']


       My name is adrian.
       ).

期望的输出

(:,
        i=0

               [John]


               [Tim]


               [Sarah]




       My name is adrian.
       ).

最佳答案

您正在输出查询集/可迭代对象,即实例

相反,您需要输出它的每个元素,即 name,正如您在 for 循环中正确声明的那样。

for 的语法与 python 的语法相同(参见 if this helps )

所以只需更换

{{instance}}

{{name}}

在模板中,您应该得到所需的输出

这意味着模板应该是

(:,

{% for name  in instance  %}
       {{name}}
{% endfor %}

 My name is {{my_name}}.
(:,

顺便说一句,我可以看到查询集有五个元素(同一行重复了五次,因为循环在五个元素上运行),但最后两个缺少名称,因为只出现了 John、Tim 和 Sarah。

关于python - 如何在 Django 中迭代数组中的所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33269901/

相关文章:

python - 在 Python 中绘制特定列值

python - 按多列将 csv 文件拆分为 Pandas 数据框

python - 使用 ArrayLike 时出现 Mypy 错误

python - 使用 Django 和 matplotlib 进行动态绘图

python - 如何在 R 中将交互式绘图保存为本地文件?

java - 数组中的定位不匹配

python - 为什么我的错误没有被捕获?

c++ - 查找一个数组作为另一个数组的子字符串

php - 使用 PHP 数组输出 MySQL 查询 - foreach 循环错误 "illegal offset"和 "invalid argument"

python - 试图理解为什么只在第一次调用嵌套 for 循环