1. 程式人生 > 其它 >python錯誤:ValueError: Sample larger than population or is negative

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