存储随机数的出现

时间:2015-12-17 15:47:41

标签: python

说我在Python中有这样的东西

from random import randint

for i in range(50):
   print randint(1, 10)

如何存储打印的次数1打印的次数2等等。

2 个答案:

答案 0 :(得分:1)

在python中,Counter通常用于计算出现次数。您只需将生成的随机值保存在变量中,并在每次迭代中更新计数器。

from __future__ import print_function
from collections import Counter
import random

cntr = Counter()
for _ in range(50):
    rnd = random.randint(1, 10)
    cntr.update([rnd])
    print(rnd)

for value, count in cntr.most_common():
    print("%d was generated %d times" % (value, count)) 

答案 1 :(得分:1)

没有Counter的替代方式。 只是简单的字典用法。

#!/usr/bin/env python
from random import randint

info = {}

for i in range(50):
    rand_val = randint(1, 10)

    if rand_val not in info.keys():
        info[rand_val] = 0

    info[rand_val] += 1

    print(rand_val)

print()
for value, cnt in info.items():
    print("value %s is generated %s times" % (value, cnt))