【问题标题】:Unreachable code block (in python) with html templater使用 html 模板程序无法访问的代码块(在 python 中)
【发布时间】: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)

困难在于模板,特别是:访问行的第二个单元格的行对象而不会导致&lt;/tr&gt; 结束标记。我必须通过row 对象创建新单元格,否则如果我调用c_table.tr.td,它会用&lt;/tr&gt; 关闭该行并开始一个新单元格。

谁能聪明地想出任何代码技巧来实现我在这种情况下尝试做的事情?

【问题讨论】:

    标签: python html conditional-statements scope


    【解决方案1】:

    您无法访问该行对象,因为它是在第一个 if 中创建的。为了在“else”中访问它,您必须在两个子句之外创建它,这无助于您实现目标。

    尝试将列表划分为“块” - 每个列表包含 2 个对象。

    h = HTML()
    comments=["blah1",
             "blah2",
             "blah3",
             "blah4",
             "blah5"
             ]
    
    fixed_list = []
    for i in xrange(0, len(comments), 2):
        fixed_list.append(comments[i:i+2])
    

    现在固定列表看起来像这样 -

    [["blah1", "blah2"], ["blah3", "blah4"], .....]
    

    现在您可以轻松地遍历该列表,并为每个列表创建一行 -

    #create table object
    body = h.body
    tb = body.table
    
    for comments_list in fixed_list:
        row = tb.tr
        for comment in comments_list:
            row.td(comment)
    
    print h 
    

    【讨论】:

      【解决方案2】:

      您的评论完全不正确。 Python 没有块作用域,if 块中定义的行可以在 else 中访问。

      事实上,你可以把 td 从 if 块中取出,把 else 完全去掉。

      【讨论】:

      • 您的回答似乎不正确。如果我将row.td(comment) 从块中取出并删除else 块,我会得到NameError: name 'row' is not defined。同样,如果我按原样运行代码。示例代码应该可以直接粘贴到您的解释器中...
      • 那是因为你的逻辑不对。索引是从 0 开始的,所以第一次通过循环 i % 2 是 0,并且没有定义行。您应该将 != 更改为 ==
      • 知道了。就我而言,巨大的手掌。谢谢丹尼尔。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多