【问题标题】:How to display a numpy array of matrix in specific format in Django template?如何在 Django 模板中以特定格式显示一个 numpy 矩阵数组?
【发布时间】:2020-05-19 14:57:02
【问题描述】:

我想在给定的板上显示数组元素。但是我做不到。

这是我的views.py:

from django.shortcuts import render
from django.http import HttpResponse
import numpy as np 
import random 
from time import sleep 


#the home will accept request when the client will send it
def play(request):
    #for request a response is created 
    #in HTTP format(changed)
    return render(request,'play.html',{'name':'M'})


# Creates an empty board 
def create_board(request):
    arr=np.array([[0, 0, 0], [0, 0, 0], 
                     [0, 0, 0]])
    return render(request,'play.html',{'array':arr})

以下是 HTML 代码:

<table>
    <tr>
        <td></td>
        <td class="vert"></td>
        <td></td>
    </tr>
    <tr>
        <td class="hori">{{array}}</td>
        <td class="vert hori"></td>
        <td class="hori"></td>
    </tr>
    <tr>
        <td></td>
        <td class="vert"></td>
        <td></td>
    </tr>
</table>

下面是我希望显示数组元素的网页表格:

编辑 1: 这就是我尝试创建表的方式:

<table>
  {% for row in array %}
  <tr>
    {% if forloop.first or forloop.parentloop.first%}
      <td class="hori"></td>
    {% else %}
      <td></td>
    {% endif %}


    {% for col in row %}
      {% if forloop.first or forloop.parentloop.first %}
        <td class="vert"></td>
      {% else %}
        <td></td>
      {% endif %}
    {% endfor %}
  </tr>
  {% endfor %}
</table>

【问题讨论】:

标签: python django numpy django-views django-templates


【解决方案1】:

我认为您可以通过执行以下操作来实现您真正想要的:

<table>
    <tr>
        <td>{{ array.0.0 }}</td>
        <td class="vert">{{ array.0.1 }}</td>
        <td>{{ array.0.2 }}</td>
    </tr>
    <tr>
        <td class="hori">{{ array.1.0 }}</td>
        <td class="vert hori">{{ array.1.1 }}</td>
        <td class="hori">{{ array.1.2 }}</td>
    </tr>
    <tr>
        <td>{{ array.2.0 }}</td>
        <td class="vert">{{ array.2.1 }}</td>
        <td>{{ array.2.2 }}</td>
    </tr>
</table>

在这里,我们将一个一个地显示矩阵的每个元素。
例如:{{ array.0.1 }} 表示显示位置在数组第 0 行第 1 列的元素。

编辑 1: 如果您有很多矩阵或更大范围的矩阵,那么上述解决方案肯定根本没有效率。但是由于您的要求是将这些“vert”和“hori”css 类仅用于特定的表格数据单元格,因此使用 for 循环和 if 条件以及实现几个 for 循环和几十个 if 来实现所需的结果变得更加困难如果您尝试将此要求仅应用于一个 3x3 矩阵,则条件是不明智的。

如果您可以将 'vert' 和 'hori' css 类应用于所有表格数据单元格,那么更优雅的解决方案是:

<table>
    {% for row in array %}
    <tr>
        {% for cell in row %}
        <td class="vert hori">{{ cell }}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>

【讨论】:

  • 它给出以下错误:TemplateSyntaxError at / 无法解析余数:'[0][0]' from 'array[0][0]'
  • 如果我应用编辑 1 代码,则不会产生任何输出
  • @Maansi 我忘记了在 django 模板中,假设使用点运算符而不是通常的类似 python 的语法来访问特定的数组元素。因此,而不是 array[0][0] put array.0.0 我已经相应地更新了我的答案。它现在应该可以工作了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 2020-06-16
相关资源
最近更新 更多