【问题标题】:Formatting API List with for loop in a Table在表格中使用 for 循环格式化 API 列表
【发布时间】:2019-07-18 15:46:05
【问题描述】:

我想在表格中输出我从 API 获得的列表,以便看起来更好。 来自 API 的数据通过 for 循环返回。我现在的问题是我不知道如何让标头每次都没有循环。

例如:

我想要一个标题,其余的在标题下

我已经从这里得到了一些说明,数据将在表格中完全显示为“制表”。 但是,每次运行时都会再次插入“标题”。

head = ["Datum", "Username", "License Server", "Feature Name", "Max. Usage", "Hours Used", "Max Used", "Hours Borrowed", "Max Borrowed"]

for item in (data['data'])
   if item['un'] == tecNo:
      print(tabulate([[item['fud'], item['un'], str(item['lsn']), str(item['fns']), str(item['musage']), str(item['hu']), str(item['mu']), str(item['hb']), str(item['mb'])]],headers=head, tablefmt="grid"))```


  [1]: https://i.stack.imgur.com/ZHODf.png
  [2]: https://i.stack.imgur.com/pNci2.png

【问题讨论】:

  • 您应该阅读How to create a Minimal, Reproducible Example,因为目前您的问题不在主题范围内,因为我们无法运行或测试它。
  • tabulate函数来自什么包?
  • 嘿,它的导入来自 Tabulate "from tabulate import tabulate"

标签: python python-3.x tabulate


【解决方案1】:

您需要将项目放在一个二维数组中,然后在最后调用tabulate

table = []
for item in (data['data'])
   if item['un'] == tecNo:
      table.append([
          item['fud'], 
          item['un'], 
          str(item['lsn']), 
          str(item['fns']), 
          str(item['musage']), 
          str(item['hu']), 
          str(item['mu']), 
          str(item['hb']), 
          str(item['mb'])
      ])
tabulate(table, headers=head)

【讨论】:

    猜你喜欢
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 2021-11-19
    相关资源
    最近更新 更多