1

サイズが 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 を超えるランダムな文字列を生成する方法を教えてください。また、なぜこの例外なのですか?

4

3 に答える 3

1

random.sample はサブセットを提供します。

問題に対する非常に最適化されていない解決策は次のとおりです。http://codebunk.com/bunk#-IviyCJW-nmi8Lr0q_74

import random
import string

print ''.join([random.choice(string.letters+string.digits) for e in range(100)])
于 2013-05-29T06:31:05.593 に答える