Python的听课笔记案例7--模拟掷硬币3.0

原创
小哥 3年前 (2022-10-28) 阅读数 6 #大杂烩

一、matplotlib模块

1、matplotlib是一个数据可视化函数库
2、matplotlib的子模块pyplot提供了2D图表制作的基本功能
3、例子:https://matplotlib.org/gallery.html

二、语法

1,散点图绘制
import matplotlib.pyplot as plt

x,y分别是x坐标和y坐标列表

plt.scatter(x,y)
plt.show()

三、实例

"""
    作者:lanxingbudui
    功能:模拟骰子
    版本:1.0
    2.0新功能:模拟掷两个骰子
    3.0新功能:可视化掷两个骰子的结果
    日期:10/24/2019
"""
import random
import matplotlib.pyplot as plt

def roll_dice():
    """
        模拟骰子
    """
    roll = random.randint(1, 6)
    return roll

def main():
    """
        主函数
    """
    total_times = 100

    # 初始化列表 [0, 0, 0, 0, 0, 0]
    result_list = [0] * 11

    # 初始化点列表
    roll_list = list(range(2, 13))
    roll_dict = dict(zip(roll_list, result_list))

    # 记录掷骰子的结果
    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()

多难看的照片啊!

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除