Pygal的官方网站:http://www.pygal.org/
官方网站
掷一个骰子
import pygal
from random import randint
class Die():
'''表示一个骰子的类'''
def __init__(self,num_sides=6):
'''骰子默认6面'''
self.num_sides = num_sides
def roll(self):
'''返回一个随机值,范围1~num_sides'''
return randint(1,self.num_sides)
#分析抛掷一个骰子的结果
die = Die()
results = []
for i in range(1000):
result = die.roll()
results.append(result)
#分析结果
fres = []
for value in range(1,die.num_sides+1):
fre = results.count(value)
fres.append(fre)
#对结果进行可视化
hist = pygal.Bar()
hist.title = "Results of rolling one D6 1000 times"
hist.x_labels = list('123456')
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add('D6',fres)
hist.render_to_file('die_visual.svg')
#查看图表 file:///F:/Spy_code/die_visual.svg
抛掷两个骰子
#创建两个D6骰子
die_1 = Die()
die_2 = Die()
#抛掷多次将结果存到列表中
results = []
for roll_num in range(1000):
res = die_1.roll() + die_2.roll()
results.append(res)
#分析结果
fres = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(1,max_result+1):
fre = results.count(value)
fres.append(fre)
#可视化结果
hist = pygal.Bar()
hist.title = 'Resuls of rolling two D6 dice 1000 times'
hist.x_labels = list('123456789')+['10','11','12']
hist.x_title = 'Result'
hist.y_title = 'Frequency of Result'
hist.add('D6',fres)
hist.render_to_file('dice_visual.svg')
#查看图片file:///F:/Spy_code/dice_visual.svg
抛掷两个不同面的骰子
#创建一个6面骰子和一个10面骰子
die_1 = Die()
die_2 = Die(10)
#抛掷多次将结果存到列表中
results = []
for roll_num in range(50000):
res = die_1.roll() + die_2.roll()
results.append(res)
#分析结果
fres = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(2,max_result+1):
fre = results.count(value)
fres.append(fre)
#可视化结果
hist = pygal.Bar()
hist.title = 'Resuls of rolling a D6 and D10 50000 times'
hist.x_labels = list('23456789')+['10','11','12','13','14','15','16']
hist.x_title = 'Result'
hist.y_title = 'Frequency of Result'
hist.add('D6+D10',fres)
hist.render_to_file('diceD10D6_visual.svg')
for index,val in enumerate(([1,2,3],'a')): #返回一个可迭代对象的索引以及值
print(index,val)