ValueError: empty range for randrange() (0, 0, 0)

简介: ValueError: empty range for randrange() (0, 0, 0)

运行环境,报错信息、原因和解决方案:

Linux系统,Python3,random包。(在运行过程中使用了其他框架,与本错误无直接关系)


报错信息:


Traceback (most recent call last):
  File "my_path/myscript.py", line 302, in <module>
    i=random.randint(0,len(val_data)-1)
  File "mypath/lib/python3.8/random.py", line 248, in randint
    return self.randrange(a, b+1)
  File "mypath/lib/python3.8/random.py", line 226, in randrange
    raise ValueError("empty range for randrange() (%d, %d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0, 0, 0)


问题所在:我发现是因为获取数据(val_data)的过程中出现了问题,导致val_data为空列表,len(val_data)-1为-1,小于0,而random.randint()方法的第二个参数必须大于或等于第1个参数。


解决方式:使randint()的第二个入参大于等于第一个入参,本例中即要求len(val_data)-1>0。

我修改获取数据的代码后,val_data有了元素,len(val_data)-1大于等于0了,就可以正常运行了。


相关文章
|
8月前
|
Python
Python报错ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Python报错ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
|
6天前
|
Python
完美解决丨2. `TypeError: list indices must be integers or slices, not str`
完美解决丨2. `TypeError: list indices must be integers or slices, not str`
ValueError: not enough values to unpack (expected 3, got 2)
这个错误通常是因为在解包(unpacking)元组(tuple)时,元组中的元素数量与期望不符,导致无法将所有元素正确解包。 例如,在以下代码中,元组中只有两个元素,但我们尝试将其解包为三个变量:
385 0
|
Python
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or
408 0
TypeError: cannot concatenate ‘str‘ and ‘list‘ objects
TypeError: cannot concatenate ‘str‘ and ‘list‘ objects
成功解决raise KeyError(f“None of [{key}] are in the [{axis_name}]“)KeyError: “None of [Index([‘age.in.y
成功解决raise KeyError(f“None of [{key}] are in the [{axis_name}]“)KeyError: “None of [Index([‘age.in.y
|
索引 Python
成功解决ValueError: column index (256) not an int in range(256)
成功解决ValueError: column index (256) not an int in range(256)
成功解决ValueError: column index (256) not an int in range(256)
|
存储 索引
成功解决ValueError: If using all scalar values, you must pass an index
成功解决ValueError: If using all scalar values, you must pass an index
成功解决ValueError: With n_samples=0, test_size=0.3 and train_size=None, the resulting train set will be
成功解决ValueError: With n_samples=0, test_size=0.3 and train_size=None, the resulting train set will be
成功解决ValueError: With n_samples=0, test_size=0.3 and train_size=None, the resulting train set will be
成功解决ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or
成功解决ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or