【Python小试】使用列表解析式简化代码
作者:互联网
列表解析式的好处:
- 代码简洁
- 可读性强
- 运行快
示例
来自《Python编程》中的一个例子:同时投掷两颗面数不同的骰子(如一个6面的D6和一个10面的D10)n次,统计两个骰子点数之和,并用Pygal绘制bar图,进行交互可视化。
不用列表解析
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')
可视化结果
标签:title,Python,die,results,列表,hist,num,小试,sides 来源: https://www.cnblogs.com/jessepeng/p/12891893.html