【Python小试】使用列表解析式简化代码
2021-01-22 06:13
标签:time sel add https and val 代码简洁 pen different 列表解析式的好处: 来自《Python编程》中的一个例子:同时投掷两颗面数不同的骰子(如一个6面的D6和一个10面的D10)n次,统计两个骰子点数之和,并用Pygal绘制bar图,进行交互可视化。 【Python小试】使用列表解析式简化代码 标签:time sel add https and val 代码简洁 pen different 原文地址:https://www.cnblogs.com/jessepeng/p/12891893.html
示例
不用列表解析
from random import randint
import pygal
class Die():
‘‘‘表示一个骰子的类‘‘‘
def __init__(self, num_sides=6):
self.num_sides = num_sides
def roll(self):
return randint(1, self.num_sides)
die_1 = Die()
die_2 = Die(10)
results = []
for roll_num in range(50000):
result = die_1.roll() + die_2.roll()
results.append(result)
frequencies = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(1, max_result+1):
frequency = results.count(value)
frequencies.append(frequency)
#可视化
hist = pygal.Bar()
hist.title = ‘Results of rolling a D6 and a D10 50000 times.‘
hist.x_labels = [‘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(‘different_dice_visual.svg‘)
对以上循环都改用列表解析
from random import randint
import pygal
‘‘‘省略Class Die‘‘‘
die_1 = Die()
die_2 = Die(10)
results = [die_1.roll()+die_2.roll() for i in range(50000)]
print(results)
max_result = die_1.num_sides + die_2.num_sides
frequencies = [results.count(x) for x in range(1, max_result)]
print(frequencies)
#可视化
hist = pygal.Bar()
hist.title = ‘Results of rolling a D6 and a D10 50000 times.‘
hist.x_labels = [str(x) for x in range(2,17)]
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add(‘D6 + D10‘,frequencies)
hist.render_to_file(‘different_dice_visual.svg‘)
可视化结果
下一篇:顺序跳跃显示数组中的值
文章标题:【Python小试】使用列表解析式简化代码
文章链接:http://soscw.com/index.php/essay/45316.html