python错误:ValueError: Sample larger than population or is negative

生成指定长度的字符串:
def getRandomSet(self, bits):
"""
获取随机字符串
:param bits: 长度
:return: 字符串
"""
num_set = [chr(i) for i in range(48, 58)]
char_set = [chr(i) for i in range(97, 123)]
total_set = num_set + char_set
value_set = "".join(random.sample(total_set, bits))
return value_set

if __name__ == '__main__':
a = getRandomSet(50)
print(a)

错误:

raise ValueError("Sample larger than population or is negative")
ValueError: Sample larger than population or is negative

 

random文件中:

def sample(self, population, k)

因为使用random.sample()方式时,population这个参数的长度必须大于k,如果小于k,那么就会提示ValueError: sample larger than population

 

解决:

def getRandomSet(self, bits):
"""
获取随机字符串
:param bits: 长度
:return: 字符串
"""
num_set = [chr(i) for i in range(48, 58)]
char_set = [chr(i) for i in range(97, 123)]
total_set = num_set + char_set
value_set = "".join(random.sample(total_set, bits))
return value_set
if __name__ == '__main__':
a = getRandomSet(20)
print(a)

结果:w492lm7tp8gnqfr3zdy1
上一篇:Delphi 与 DirectX 之 DelphiX(71): TDIB.Negative;


下一篇:[C]圆的面积,macro