python矩阵的错误和输出问题?

时间:2017-03-18 20:42:17

标签: function python-3.x matrix format

我正在构建一个函数,它接受由列表组成的列表(例如:[['a'],['b'],['c']])并将其作为表输出。我不能使用漂亮的表因为我需要一个特定的输出(ex | 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

我不确定为什么会出现问题。我还得到一个输出错误,它只输出第一个列表中的第一个项目,仅此而已。有人可以解释如何使用格式函数来摆脱这个错误并输出我想要的正确吗?

修正了错误,但测试仍然失败:

失败:test_show_table_12(主要 .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 |
?    ++++     +       + +

2 个答案:

答案 0 :(得分:2)

问题在于:

for row in range(table):

range将1,2或3个整数作为参数。它没有列表。

您想使用:

for row in table:

另外,检查你的缩进;看起来新行添加应该缩进更多。

答案 1 :(得分:1)

您的追溯告诉您问题出现在第5行:

for row in range(table):

...因此,该行上的某些内容正在尝试将其他内容解释为整数,但没有成功。如果我们查看range()的{​​{3}},我们会看到:

  

范围构造函数的参数必须是整数(内置int或任何实现__index__特殊方法的对象)。

...但table不是整数;这是一个清单。如果你想迭代一个列表(或类似的东西),你就不需要一个特殊的功能 - 只需

for row in range:

工作得很好。

除了误用range()之外,您的功能存在另一个问题,即您已经缩减了过多的代码。这样:

  if table is None:
    table=[]
    new_table=""
    for row in range(table):
       for val in row:
         new_table+= ("| "+val+" ")
    new_table+= "|\n"

...如果tableNone,则只会执行缩进代码的任何,而您真正想要的只是设置table=[]如果是def show_table(table): if table is None: table=[] new_table = "" for row in table: for val in row: new_table += ("| " + val + " ") new_table += "|\n" return new_table.strip("\n") 案件。解决这两个问题可以解决这个问题:

return

(我还将所有缩进更改为四个空格,并在此处添加空格以改善样式)。