【发布时间】:2017-03-18 20:42:16
【问题描述】:
我正在构建一个函数,它接受由列表组成的列表(例如:[['a'],['b'],['c']])并将其输出为表格。我不能使用漂亮的表格,因为我需要一个特定的输出(例如 | a | b | ),其中的线条和空格完全相同。
这是我的功能:
def show_table(table):
if table is None:
table=[]
new_table=""
for row in range(table):
for val in row:
new_table+= ("| "+val+" ")
new_table+= "|\n"
return new_table.strip("\n")
我不断收到错误:
show_table([['a'],['b'],['c']])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in show_table
TypeError: 'list' object cannot be interpreted as an integer
我不确定为什么会出现问题。我也得到了一个输出错误,它只输出第一个列表中的第一个项目,仅此而已。有人能解释一下如何使用 format 函数来摆脱这个错误并正确输出我想要的吗?
已修复错误但仍无法通过测试:
失败:test_show_table_12 (main.AllTests)
Traceback (most recent call last):
File "testerl7.py", line 116, in test_show_table_12
def test_show_table_12 (self): self.assertEqual (show_table([['10','2','300'],['4000','50','60'],['7','800','90000']]),'| 10 | 2 | 300 |\n| 4000 | 50 | 60 |\n| 7 | 800 | 90000 |\n')
AssertionError: '| 10| 2| 300|\n| 4000| 50| 60|\n| 7| 800| 90000|' != '| 10 | 2 | 300 |\n| 4000 | 50 | 60 |\n| 7 | 800 | 90000 |\n'
- | 10| 2| 300|
+ | 10 | 2 | 300 |
? +++ +++ +++
- | 4000| 50| 60|
+ | 4000 | 50 | 60 |
? + ++ ++++
- | 7| 800| 90000|+ | 7 | 800 | 90000 |
? ++++ + + +
【问题讨论】:
-
请包含您收到的针对给定函数输入的确切错误消息……“列表不可迭代”不是。还要确保您在此处发布的代码是您遇到问题的确切代码;如上所述,上面的函数根本不会输出任何内容,因此它不能输出列表中的第一项。
-
我包含了我现在得到的确切错误@ZeroPiraeus
-
请在帮助文件中查看如何格式化您的帖子。
-
有关如何正确格式化您的问题(包括代码等)的说明可在here 获得。
标签: function python-3.x matrix format