【问题标题】:assert(len(content) == 3) AssertionError断言(len(内容)== 3)断言错误
【发布时间】:2021-02-07 05:57:18
【问题描述】:

我收到了这个错误

cluster.py", line 20, in load_data
   distance, num, max_dis, min_dis = load_data(distance_file)
    assert(len(content) == 3)
AssertionError

cluster.py的代码

with open(distance_file, 'r', encoding = 'utf-8') as infile:
        for line in infile:
            content = line.strip().split(' ')
            assert(len(content) == 3)
            idx1, idx2, dis = int(content[0]), int(content[1]), float(content[2])

数据样例

1   1   0.000000
1   2   26.232388
1   3   44.486252
1   4   47.168839
1   5   37.593277

另一个文件的样本是

-82.3602 158.46
-91.0108 133.695
-125.815 148.936
-129.259 153.42

【问题讨论】:

  • 永远不要使用.split(' '),除非您特别只想在一个空格上分割。我想你实际上想要.split(),它在一个或多个任意空白字符上分割。此外,您可以通过在assert 之前的行上添加print(content) 来轻松地自行调试。
  • 是的,这些列之间显然有多个空格...
  • 我试过了,错误仍然 assert(len(content) == 3) AssertionError
  • 你试过print(content)吗?因为如果你这样做了,它失败的原因就会变得很明显,你应该发布那个输出。
  • 另外,您的回溯与代码不匹配 - 如果您能证明它实际上与 split() 无关,我可以重新打开问题。

标签: python assert


【解决方案1】:

你得到一个AssertionError,因为断言失败,它失败了,因为你在 1 个空格上分割,但值被 2 个空格分隔。为了避免这种情况,请使用不带参数的 split ,它将以任意数量的空格进行拆分:

content = line.strip().split()

【讨论】:

  • 我试过了,错误仍然 assert(len(content) == 3) AssertionError
  • @user1 抱歉,我试过了,它可以工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-09
  • 2021-01-25
  • 2012-05-08
  • 2018-05-19
  • 2014-09-27
  • 2014-03-26
  • 1970-01-01
相关资源
最近更新 更多