乱数の取得
randomモジュールを使用する
>>> import random >>> dir(random) ['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_acos', '_ceil', '_cos', '_e', '_exp', '_hashlib', '_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'division', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate'] #0.0-1.0の乱数を返す >>> random.random() 0.8053929320762603 #引数間の乱数(float)を返す >>> random.uniform(1,2) 1.732187115057481 #引数間の乱数(int)を返す >>> random.randint(5,10) 6 #引数の要素をランダムに取得 >>> random.choice([1,2,5]) 2 >>> random.choice("string") 'g' #hashはNG >>> random.choice({"h1":"v1","h2":"v2","h3":"v3"}) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 274, in choice return seq[int(self.random() * len(seq))] # raises IndexError if seq is empty KeyError: 0 #list内の要素を無作為に並べ替え >>> list=[1,2,5] >>> random.shuffle(list) >>> list [5, 1, 2] #こちらもhashはNG >>> hash={"h1":"v1","h2":"v2","h3":"v3"} >>> random.shuffle(hash) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 288, in shuffle x[i], x[j] = x[j], x[i] KeyError: 0 >>> s="string" >>> random.shuffle(s) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 288, in shuffle x[i], x[j] = x[j], x[i] TypeError: 'str' object does not support item assignment