所以,我在最新的项目中使用表格来格式化我的数据。但是,它一直给出这个错误,我无法理解其背后的原因。代码如下:
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', '0'], [1, 1, 1, 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, headers=["Sno.", "Jades", "Event", "Date"], 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, 1]]
,它是一行(外括号)包含四列(内括号)。
我从未使用过这个库,因此我可能会在此处切换行/列,但概念是相同的。
关于python - 使用 tabulate 时出错 "TypeError: ' int' 对象不可迭代”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63538120/