# 逆流者blog / python3-learn

### 使用Pygal模拟掷骰子

.gitignore 0 → 100644
 /.idea/ /**/.idea/ /*/venv/ \ No newline at end of file
pygal/die.py 0 → 100644
 from random import randint class Die: """表示一个骰子的类""" def __init__(self, num_sides=6): """骰子默认为6面""" self.num_sides = num_sides def roll(self): """返回一个位于骰子面数的随机的值，默认1-6""" return randint(1, self.num_sides)
 import pygal from die import Die # 创建两个骰子 die1 = Die() die2 = Die() # 掷几次骰子，并将结果存储在一个列表中 results1 = [] results2 = [] for roll_num in range(1000): result1 = die1.roll() result2 = die2.roll() results1.append(result1) results2.append(result2) # 分析结果 # 分析第一个骰子的结果 frequencies1 = [] for value in range(1, die1.num_sides + 1): # count() 统计一个值在列表中出现的次数 frequency1 = results1.count(value) frequencies1.append(frequency1) # 分析第二个骰子的结果 frequencies2 = [] for value in range(1, die2.num_sides + 1): # count() 统计一个值在列表中出现的次数 frequency2 = results2.count(value) frequencies2.append(frequency2) # 对结果进行可视化 hist = pygal.Bar() hist.title = "两个骰子随机滚动1000次的结果" hist.x_labels = ['1', '2', '3', '4', '5', '6'] hist.x_title = "结果" hist.y_title = "结果频率" # 将一系列值添加到图表中 hist.add('骰子1', frequencies1) hist.add('骰子2', frequencies2) hist.render_to_file('die_visual.svg')

Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.