gpt4 book ai didi

python - 如何将python列表制作成html表格

转载 作者:太空宇宙 更新时间:2023-11-04 15:48:39 25 4
gpt4 key购买 nike

我有这个 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 if col is not none否则 '' }}.

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com