2013-05-29 25 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

是真的,但是在所有角色只采样一次之前,所以我认为这将是一个自然的扩展 –