Python-Pygal模拟掷骰子
from random import randint
# 骰子类
class Die():
def __init__(self, num_sides=6):
# 骰子的面数
self.num_sides = num_sides
def roll(self):
# 模拟投骰子
return randint(1, self.num_sides)
import pygal
from die import Die
# 创建一个骰子
die = Die()
# 生成随机投掷的数据
results = []
for x in range(1000):
results.append(die.roll())
# 统计每个数出现的频率
frequencies = []
for value in range(1, die.num_sides + 1):
count = results.count(value)
frequencies.append(count)
hist = pygal.Bar()
hist._title = "掷骰子结果分布"
hist.x_labels = ['1', '2', '3', '4', '5', '6']
hist._x_title = "结果"
hist._y_title = "出现的次数"
hist.add('六面骰子', frequencies)
# 保存为svg文件
hist.render_to_file('E:/die_result.svg')