模拟掷两个色子代码:
import random as t
def roll_dice():
roll = t.randint(1,6)
return roll
def main():
"""
主函数
"""
total_times = 1000000
#初始化列表[0,0,0,0,0,0,0,0,0,0,0]
list1 = [0] * 11
#初始化点数列表
roll_list = list(range(2,13))
roll_dict = dict(zip(roll_list,list1))
for i in range(total_times):
roll1 = roll_dice()
roll2 = roll_dice()
for j in range(2,13):
if (roll1 + roll2) == j:
roll_dict[j] += 1
for i, result in roll_dict.items():
print("点数{}的次数:{},频率{}".format(i,result,result / total_times))
if __name__ == "__main__":
main()
输出结果:
点数2的次数:27662,频率0.027662
点数3的次数:55132,频率0.055132
点数4的次数:83568,频率0.083568
点数5的次数:111308,频率0.111308
点数6的次数:138184,频率0.138184
点数7的次数:167134,频率0.167134
点数8的次数:138542,频率0.138542
点数9的次数:111404,频率0.111404
点数10的次数:83788,频率0.083788
点数11的次数:55573,频率0.055573
点数12的次数:27705,频率0.027705
数据可视化
import random as t
import matplotlib.pyplot as plt
def roll_dice():
roll = t.randint(1,6)
return roll
def main():
"""
主函数
"""
total_times = 100
#初始化列表[0,0,0,0,0,0,0,0,0,0,0]
list1 = [0] * 11
#初始化代数列表
roll_list = list(range(2,13))
roll_dict = dict(zip(roll_list,list1))
#记录色子的结果
roll1_list = []
roll2_list = []
for i in range(total_times):
roll1 = roll_dice()
roll2 = roll_dice()
roll1_list.append(roll1)
roll2_list.append(roll2)
for j in range(2,13):
if (roll1 + roll2) == j:
roll_dict[j] += 1
for i, result in roll_dict.items():
print("点数{}的次数:{},频率{}".format(i,result,result / total_times))
#数据可视化
x = range(1,total_times + 1)
plt.scatter(x,roll1_list,c = "red",alpha = 0.5)
plt.scatter(x,roll2_list,c= "green",alpha= 0.5)
plt.show()
if __name__ == "__main__":
main()
数据可视化结果:
- enumerate()函数用于将可遍历的列表转换为一个索引序列,一般用于for循环中,同时列出元素和元素的索引号。转换字典用 items() 函数。
- zip()函数用于将对应的元素打包成一个元组。
注意:元组中的数据是不可修改的,若要修改需要转换成字典或其他。
dic(zip(l1 + l2))