2013-05-29 26 views
1

當我試圖生成大小100個或更多的隨機字符串,它給了我異常...生成大小爲100以上蟒隨機字符串

msg="".join(random.sample(string.letters+string.digits,random.randint(5,100))) 

Exception: 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/lib/python2.7/random.py", line 316, in sample 
    raise ValueError, "sample larger than population" 
ValueError: sample larger than population 

你能幫我解釋一下我怎麼能生成一個大於100的隨機字符串? 以及爲什麼這個例外?

+0

取決於比'100'你想去的地方...... – jamylak

回答

3
len(string.digits + string.letters) = 62. 

random.sample函數不會對替換進行採樣,因此它不能對此列表的62個元素進行採樣。您可能想嘗試使用列表理解的方法。

+0

該死高多少!打我 – TerryA

1

你有62個角色需要吸取如果你嘗試繪製更長的樣本,你會得到例外。您可以填寫您的樣本空間至少如下所示的必要長度:

chars = string.letters + string.digits 
sample_space = chars*((100/len(chars))+1) 
msg="".join(random.sample(sample_space, random.randint(5,100))) 
+0

這會輸出一個字符串,其中每個字母和數字最多出現兩次 - 這是一個可能但不尋常的要求。 –

+0

是真的,但是在所有角色只採樣一次之前,所以我認爲這將是一個自然的擴展 –