本文是题主是闲时时间随便翻翻书跟着学的Python简易项目,参考《python编程从入门到实践》使用Pygal模拟掷骰子。
打开cmd输入
pip install --user pygal==11.7
如果你觉得安装慢可以使用阿里源
pip install --user pygal==11.7 -i http://mirrors.aliyun.com/pypi/simple --trusted-host mirrors.aliyun.com
创一个文件夹就行,更名为Pygal
创建一个Python文件并命名为dei.py
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)
创建一个Python文件并命名为die_visual.py
from Pygal.die import Die
import pygal
die = Die()
#模拟数据
results = []
for rool_num in range(10000):
result = die.roll()
results.append(result)
# print(results)
#分析数据
frequencies = []
for value in range(1 , die.num_sides + 1):
frequency = results.count(value)
frequencies.append(frequency)
print(frequencies)
#可视化数据
hist = pygal.Bar()
hist.title = "Results of rolling one D6 10000 time."
hist.x_labels = ['1','2','3','4','5','6']
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add('D6',frequencies)
hist.render_to_file('die_visual.svg')
创建一个Python文件并命名为die_visual2.py
from Pygal.die import Die
import pygal
die_1 = Die()
die_2 = Die()
#创造基础数据
results = []
for rool_num in range(1000000):
result = die_1.roll() + die_2.roll()
results.append(result)
# print(results)
#分析结果
frequencies = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(2 , max_result + 1):
frequency = results.count(value)
frequencies.append(frequency)
print(frequencies)
#可视化结果
hist = pygal.Bar()
hist.title = "Results of rolling one D6 1000000 time."
hist.x_labels = ['1','2','3','4','5','6','7','8','9','10','11','12']
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add('D6 + D6',frequencies)
hist.render_to_file('die_visual2.svg')
创建一个Python文件并命名为die_visual3.py
from Pygal.die import Die
import pygal
die_1 = Die()
die_2 = Die(10)
#创造基础数据
results = []
for rool_num in range(1000000):
result = die_1.roll() + die_2.roll()
results.append(result)
# print(results)
#分析结果
frequencies = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(2 , max_result + 1):
frequency = results.count(value)
frequencies.append(frequency)
print(frequencies)
#可视化结果
hist = pygal.Bar()
hist.title = "Results of rolling one D6 1000000 time."
hist.x_labels = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16']
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add('D6 + D10',frequencies)
hist.render_to_file('die_visual3.svg')