使用表格时出现错误“ TypeError:'int'对象不可迭代”

问题描述

所以,我使用表格来格式化我最新项目中的数据。但是,它不断出现此错误,我无法理解其背后的原因。这是代码:

   from datetime import date
   from tabulate import tabulate
   records = []
   sno = [0,1]
   jades = [0,1]
   events = ['0',1]
   dates = ['0',1]
   for i in range(0,len(jades)):
      records.append([sno[i],jades[i],events[i],dates[i]])
        
   print(records)
   record = records[-1]
   print(record)
   print(tabulate(record,headers=["Sno.","Jades","Event","Date"],tablefmt='simple'))

这是输出:

[[0,'0','0'],[1,1,1]]
[1,1]
Traceback (most recent call last):
  File "/home/kartik/Desktop/discord-bot/Rem.py",line 16,in <module>
    print(tabulate(record,tablefmt='simple'))
  File "/home/kartik/.local/lib/python3.8/site-packages/tabulate.py",line 1426,in tabulate
    list_of_lists,headers = _normalize_tabular_data(
  File "/home/kartik/.local/lib/python3.8/site-packages/tabulate.py",line 1103,in _normalize_tabular_data
    rows = list(map(list,rows))
TypeError: 'int' object is not iterable

请注意,我发布的代码只是我发现导致错误的部分。这些行号可能有所不同。

我试图弄清楚自己,但是我唯一能想到的就是这段代码:

record = [records[-1]] 

我将最后的记录转换成它自己的列表。

请帮助我了解其背后的原因。我是python的初学者,所以我的问题可能很愚蠢。

提前谢谢!

解决方法

根据documentation,要制表的第一个参数是可迭代项或类似的可迭代项,例如电子表格。您需要行和列。您传入的只是一个列表,因此在内部,它首先获取第一个元素(在您的情况下为“ 1”),将其视为一行,然后尝试遍历每一列,这是引发异常的地方

将其包裹在另一组括号中时,例如:

record = [records[-1]] 

然后,您实际上拥有[[1,1,1]],即一行(外括号)包含四列(内括号)。

我从来没有使用过这个库,所以我可能在这里切换了行/列,但是概念是相同的。

,

尝试print(tabulate(records,headers=["Sno.","Jades","Event","Date"],tablefmt='simple'))

原因是制表函数中的第一个参数需要一个类型表对象。在您当前的代码中,record被设置为记录列表中的最后一个整数。 Tabulate需要一个表进行迭代,因此请传递记录列表

,

在这里尝试recordsrecord

print(tabulate(records,headers=["Sno",tablefmt='simple'))

它的作品

[[0,'0','0'],[1,1]]
[1,1]
  Sno    Jades    Event    Date
-----  -------  -------  ------
    0        0        0       0
    1        1        1       1

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...