Search code examples
pythonassert

assert(len(content) == 3) AssertionError


I got this error

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

the code of 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])

sample of data like

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

sample of the other file is

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

Solution

  • You get an AssertionError, because the assertion fails, and it fails, because you are splitting on 1 space, but the values are separated by 2 spaces. To circumvent this, use split without arguments, which will split at arbitrary amounts of spaces:

    content = line.strip().split()