个人博客页面链接:http://www.shihao.online/(django搭建的个人博客,还在完善中)
#encoding:utf-8
import pygal
from random import randint
class Die():
'''表示一个筛子的类'''
def __init__(self, num_size = 6):
'''筛子默认为6面'''
self.num_size = num_size
def roll(self):
'''返回一个位于1和筛子面数之间的随机值'''
return randint(1, self.num_size)
die = Die()
#掷几次筛子,并将结果存储到一个列表中
results = []
for roll_num in range(1000):
result = die.roll()
results.append(result)
''' #输出掷筛子的结果 a = 0 for i in results: print("%d"%(i), end = ' ') #print(i, end =' ') a = a + 1 if a % 10 ==0: print() '''
#分析各个面出现的次数
frequencies = []
for value in range(1, die.num_size + 1):
frequency = results.count(value)
frequencies.append(frequency)
#对结果进行可视化
hist = pygal.Bar()
hist.title = "Result of rolling one D6 1000 times."
hist.x_labels = ['1', '2', '3', '4', '5', '6']
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add('D6', frequencies)
hist.render_to_file('使用pygal模拟掷筛子.svg')