源码如下:
1 # pygal包:生成可缩放的矢量图形文件,可自适应不同尺寸的屏幕显示 2 # 安装:python -m pip intall pygal-2.4.0-py2.py3-none-any.whl 3 # 功能:掷一个骰子统计次数并以直方图形式显示 4 import pygal 5 from die_class import Die 6 7 die = Die() # 实例化一个骰子对象 8 9 results = [] 10 # 掷骰子100次 11 for n in range(100): 12 res = die.roll() 13 results.append(res) 14 15 print(results) 16 17 frequencies = [] 18 # 统计每个面出现的次数 19 for value in range(1, die.num_sides + 1): 20 frequency = results.count(value) 21 frequencies.append(frequency) 22 23 print("骰子各面出现的次数:", frequencies) 24 25 # 使用pygal以直方图形式显示统计结果 26 hist = pygal.Bar() 27 hist.title = ‘掷骰子100次统计结果‘ 28 hist.x_labels = [‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘] 29 30 hist.x_title = ‘骰子结果‘ 31 hist.y_title = ‘出现次数‘ 32 33 hist.add(‘六面的骰子‘, frequencies) 34 hist.render_to_file(‘D:\pywork\output\pygal\die_visual.svg‘)
die_class.py:
1 # 骰子类 2 from random import randint 3 4 5 class Die(): 6 ‘‘‘表示一个骰子类‘‘‘ 7 8 def __init__(self, num_sides=6): 9 ‘‘‘骰子默认为6面‘‘‘ 10 self.num_sides = num_sides 11 12 def roll(self): 13 ‘‘‘返回一个位于1与面数之间的随机数‘‘‘ 14 return randint(1, self.num_sides)
运行结果:
1 [2, 3, 6, 6, 1, 3, 1, 3, 1, 3, 1, 3, 6, 2, 1, 5, 5, 3, 6, 5, 1, 3, 4, 3, 3, 4, 2, 2, 3, 3, 4, 6, 1, 3, 1, 5, 5, 5, 5, 1, 3, 5, 5, 3, 5, 4, 3, 2, 5, 2, 1, 1, 2, 6, 6, 4, 4, 2, 1, 3, 3, 2, 5, 3, 1, 1, 3, 4, 1, 2, 1, 2, 1, 2, 6, 1, 3, 3, 6, 6, 3, 1, 1, 2, 4, 5, 4, 3, 2, 1, 6, 6, 6, 2, 6, 1, 4, 3, 1, 1] 2 骰子各面出现的次数: [24, 15, 24, 10, 13, 14]
运行截图:
时间: 2024-10-27 04:00:58