Flask接口签名sign原理与实例代码浅析
293
2022-08-31
【Python小试】使用列表解析式简化代码(列表推导式python菜鸟教程)
列表解析式的好处:
代码简洁可读性强运行快
示例
来自《Python编程》中的一个例子:同时投掷两颗面数不同的骰子(如一个6面的D6和一个10面的D10)n次,统计两个骰子点数之和,并用Pygal绘制bar图,进行交互可视化。
不用列表解析
from random import randintimport pygalclass 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_sidesfor 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 randintimport 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_sidesfrequencies = [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')
可视化结果
作者:Bioinfarmer
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~