python - 如何将python列表转为html表格

标签 python html python-3.x

我有这个 python 列表

result =[('921', 36638, None, None, 'ron', '28-SEP', 'platform'),
('921', 36637, None, None, 'john', '28-SEP', 'platform')]

此列表中的值是动态的。但是表头始终是静态的。

Table header: 
Issue   Vers    created_on  Build   Author  Commit  Source_Name

我想更改此 python 输出并将其制作成 HTML 表格。

这是我迄今为止的工作

z = import result
s =open(z)

table=['<htm><body><table border="1">']
for line in s.splitlines():
    if not line.strip():
        continue
    table.append(r'<tr><td>{}</td><td>{}</td></tr>'.format(*line.split('--- ')))

table.append('</table></body></html>')
print ''.join(table)    

我对放置静态 header 感到困惑。谢谢

最佳答案

这可能是 jinja 的情况模板:

from jinja2 import Template

t = Template('''
<html>
  <body>
    <table border="1">

      <tr>
      {%- for col in header %}
        <td>{{col}}</td>
      {%- endfor %}
      </tr>

      {% for row in rows -%}
      <tr>
      {%- for col in row %}
        <td>{{col if col is not none else '' }}</td> 
      {%- endfor %}
      </tr>
      {% endfor %}

    </table>
  </body>
</html>
''')


header = 'Issue Vers created_on Build Author Commit Source_Name'.split()
rows = [('921', 36638, None, None, 'ron', '28-SEP', 'platform'),
        ('921', 36637, None, None, 'john', '28-SEP', 'platform')]

strg = t.render(header=header, rows=rows)

如果您不想在表格中打印 None,则可以将 {{col}} 替换为 {{col 如果 col 不是 none否则'' }}

关于python - 如何将python列表转为html表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52620805/

相关文章:

python - numpy 将二维数组保存到文本文件

python - 为不规则间隔的数据找到最接近特定时间的每日观察

python - youtube api - 从视频元数据中检索 "music in this video"信息?

html - div的背景图片

python-3.x - 电子邮件未发送excel附件

python - 在 Python 中导入 PIL (Pillow) 模块

Python:如何判断一个字符串是代表语句还是表达式?

javascript - 从数独表 HTML 表生成数字数组

html - CSS:渲染图像时保持纵横比

mysql - 在 Django Python 中删除元素后重新排序数据库