python--pygal
阿新 • • 發佈:2018-12-12
建立一個Die的類
from random import randint
import random
class Die():
def __init__(self,num_sides=6):
self.num_sides=num_sides
def roll(self):
return random.randint(1,self.num_sides)
將類進行例項化
from D6 import Die die = Die() results = [] for roll_num in range(100): result = die.roll() results.append(result) #print(results) frequencies = [] for value in range(1,die.num_sides+1): frequencie = results.count(value) frequencies.append(frequencie) print(frequencies) import pygal hist = pygal.Bar() hist.title = '一個色子投擲一百次的結果' hist.x_labels =list('123456') hist.x_title = '結果' hist.y_title = '次數' hist.add('D6',frequencies) hist.render_to_file('D6_visual.svg')
實現列表視覺化,儲存為svg形式的檔案
同時丟三個色子
from D6 import Die die1 = Die() die2 = Die() die3 = Die() results = [] for roll_num in range(100000): result = die1.roll() + die2.roll() + die3.roll() results.append(result) frequencies = [] max_result = die1.num_sides + die2.num_sides +die3.num_sides for value in range(3,max_result+1): frequencie = results.count(value) frequencies.append(frequencie) import pygal hist = pygal.Bar() hist.title = '三個色子投擲十萬次的結果' hist.x_labels =list(range(3,19)) hist.x_title = '結果' hist.y_title = '次數' hist.add('D63',frequencies) hist.render_to_file('D63_visual.svg')