首页 > 解决方案 > 烧瓶表仅显示 Python 列表中的第一行,for 循环不适用于行

问题描述

新手来了 有一个令我沮丧的问题。我有一个烧瓶表应该显示来自 python 的列表,但它只显示 python 列表中的第一行。

这就是我在 Visual Studio 代码中运行 py 脚本时 python 列表输出的样子。

[('location 123', 'Hello Street', 'Los Angeles', 1.0, 40, 3, '2021-08-28T02:28:21.000000Z')]
[('location xyz', 'Beta Rd', 'Burlington', 1.0, 40, 2, '2021-08-28T00:30:36.000000Z')]
[('location abc', 'Alpha Ave', 'Seattle', 1.0, 40, 0, '2021-08-25T03:53:26.000000Z')]

这些行是动态的,因此并非每个列表都有固定的数量。

第一行显示正确,以及标题和所有内容。但我无法显示额外的行。

这是设置输出的 main.py 行

return render_template("result.html", headings=headings, output=city_details())

这是我的 result.html 文件

  <body>
  
    <h1>Results</h1>

    <table class="table">
      <tr class="table__header">
        {% for header in headings %}
        <th class="table__cell">{{ header }}</th>
        {% endfor %}
      </tr>

      {% for row in output %}
      <tr class="table__row">
        {% for cell in row %}
        <td class="table__cell">{{cell}}</td>
        {% endfor %}
      </tr>
      {% endfor %}
    </table>
  </body>

这是设置列表的python脚本的一部分

for details in data:
   location = details['location']
   street = details['street']
   city = details['city']
   scale = details['scale']
   etc...
   city_details = location, street, city, scale
   total_details = [city_details]
   return total_details

有人知道我的 for 循环表有什么问题吗?还是我的清单做错了?我猜这是我忽略的非常简单的事情,但我无法弄清楚并让自己发疯。

提前致谢。

标签: pythonpython-3.xflaskhtml-table

解决方案


您显示的代码位相当于

details = data[0]
location = details['location']
street = details['street']
city = details['city']
scale = details['scale']
# ... any additional processing ...
city_details = location, street, city, scale
total_details = [city_details]
return total_details

因为您在循环内进行了无条件返回。

我会编写一个单独的函数,details然后city_details使用列表理解:

# earlier in your code, add this top-level function:
def make_table_row(details):
    location = details['location']
    street = details['street']
    city = details['city']
    scale = details['scale']
    # ... any additional processing ...
    return location, street, city, scale

# replace your original loop with this:
return [make_table_row(details) for details in data]

推荐阅读