【发布时间】:2015-02-23 15:51:58
【问题描述】:
我在 python 3.4 中创建一个复杂的 html 表时遇到了麻烦。模板是html 1.16。这是问题的简化版本:我想遍历一个列表。对于每个列表项,我想将数据写入 html 表。该表应为两列宽。
from html import HTML
#create html object
h = HTML()
comments=["blah1",
"blah2",
"blah3"
]
#create table object
c_table = h.table.tbody
for i, comment in enumerate(comments):
#create row if we are at an odd index
if i % 2 != 0:
row = c_table.tr
row.td(comment)
else:
#it is intended to add another <td> to the current row here
#but because the row was declared in the if block, it is out of scope
row.td(comment)
#write the html output now
print(h)
困难在于模板,特别是:访问行的第二个单元格的行对象而不会导致</tr> 结束标记。我必须通过row 对象创建新单元格,否则如果我调用c_table.tr.td,它会用</tr> 关闭该行并开始一个新单元格。
谁能聪明地想出任何代码技巧来实现我在这种情况下尝试做的事情?
【问题讨论】:
标签: python html conditional-statements scope