# 逆流者blog / python3-learn

die_visual.py 1.1 KB
 逆流者blog 已提交 10月 22, 2020 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 ``````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')``````