我有这个 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/