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了,就可以正常运行了。


相关文章
|
3月前
|
Python
ValueError: sleep length must be non-negative
ValueError: sleep length must be non-negative
102 3
|
5月前
|
数据处理 开发者 Python
【Python】已解决:ValueError: Length mismatch: Expected axis has 5 elements, new values have 4 elements
【Python】已解决:ValueError: Length mismatch: Expected axis has 5 elements, new values have 4 elements
404 9
|
7月前
|
Python
完美解决丨2. `TypeError: list indices must be integers or slices, not str`
完美解决丨2. `TypeError: list indices must be integers or slices, not str`
报错 ValueError: too many values to unpack (expected 2)
报错 ValueError: too many values to unpack (expected 2)
221 0
ValueError: not enough values to unpack (expected 3, got 2)
这个错误通常是因为在解包(unpacking)元组(tuple)时,元组中的元素数量与期望不符,导致无法将所有元素正确解包。 例如,在以下代码中,元组中只有两个元素,但我们尝试将其解包为三个变量:
659 0
TypeError: randint() received an invalid combination of arguments - got (int, int, int), but expecte
TypeError: randint() received an invalid combination of arguments - got (int, int, int), but expecte
715 0
TypeError: cannot concatenate ‘str‘ and ‘list‘ objects
TypeError: cannot concatenate ‘str‘ and ‘list‘ objects
|
索引 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)
成功解决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
|
存储 索引
成功解决ValueError: If using all scalar values, you must pass an index
成功解决ValueError: If using all scalar values, you must pass an index