【发布时间】:2019-12-11 14:58:30
【问题描述】:
我有以下问题。
我有这些功能:
def string_to_2Darray(flat_string):
"""converts a string of type '0,1,0,1,1,1,0,1,0'"""
array1d = np.fromstring(flat_string, dtype=int, sep=',')
return np.reshape(array1d, (-1,3))
我为此函数编写了一个单元测试类,如下所示:
class StringTo2DArray(unittest.TestCase):
def test_string_2DArray(self):
string_example_0 = '0,1,0,1,1,1,0,1,0'
array_example_0 = string_to_2Darray(string_example_0)
print(array_example_0)
print(type(array_example_0))
self.assertEqual([[0,1,0],[1,1,1],[0,1,0]], array_example_0)
看到我在 unittest 的 StringTo2DArray 类的 test_string_2Darray 模块的主体中添加了一些打印语句。
当我运行 python -m unittest 时,我收到以下错误消息:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
我不知道为什么会发生这种情况,因为字符串已正确转换为 2D numpy 数组,并且与我在断言中传递的数组 [[0,1,0],[1,1,1],[0,1,0]] 不匹配。等于我的测试。
【问题讨论】:
标签: python arrays numpy unit-testing