本文主要是介绍python 列表解析式_【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')
可视化结果
这篇关于python 列表解析式_【Python小试】使用列表解析式简化代码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!