Python Docstring如何在docstring的多行中编写列表?

时间:2019-04-17 06:39:26

标签: python python-3.x doctest

我试图编写一个列表输出,将其在doctest中扩展为多行。但是实际输出却与我的预期不符。

这是我的代码。

def make_board(dimension: int, queens: list):
    """

    >>> make_board(4, [(0, 1), (1, 3), (2, 0), (3, 2)])
    [[False, True, False, False],
     [False, False, False, True],
     [True, False, False, False],
     [False, False, True, False]]
    """
    assert dimension == len(queens)
    return [[(row, col) in queens for col in range(dimension)] for row in range(dimension)]

这是测试结果

Failed example:
    make_board(4, [(0, 1), (1, 3), (2, 0), (3, 2)])
Expected:
    [[False, True, False, False],
     [False, False, False, True],
     [True, False, False, False],
     [False, False, True, False]]
Got:
    [[False, True, False, False], [False, False, False, True], [True, False, False, False], [False, False, True, False]]

2 个答案:

答案 0 :(得分:1)

使用NORMALIZE_WHITESPACE选项。可以通过不同的方式来启用它,例如通过docstring中的指令:

def make_board(dimension: int, queens: list):
    """
    >>> make_board(4, [(0, 1), (1, 3), (2, 0), (3, 2)]) # doctest: +NORMALIZE_WHITESPACE
    [[False, True, False, False],
     [False, False, False, True],
     [True, False, False, False],
     [False, False, True, False]]
    """

答案 1 :(得分:0)

如果您希望看到漂亮的结果,则可以为此内置pprint:

from pprint import pprint

def make_board(dimension: int, queens: list):
"""

>>> make_board(4, [(0, 1), (1, 3), (2, 0), (3, 2)])
[[False, True, False, False],
 [False, False, False, True],
 [True, False, False, False],
 [False, False, True, False]]
"""
assert dimension == len(queens)

result = [[(row, col) in queens for col in range(dimension)] for row in range(dimension)]
pprint(result)

return result

每次调用函数时都会看到结果,所以我不建议这样做。

>>>a=make_board(4, [(0, 1), (1, 3), (2, 0), (3, 2)])
[[False, True, False, False],
[False, False, False, True],
[True, False, False, False],
[False, False, True, False]]

>>>a
[[False, True, False, False], [False, False, False, True], [True, False, False, False], [False, False, True, False]]