Random
随机掷骰子基础代码:
import random
def roll_dice():
roll = random.randint(1, 6)
return roll
def main():
total_times = 10
# 初始化列表 [0,0,0,0,0,0] 记录每个点出现的次数
result_list = [0]*6
for i in range(total_times):
roll = roll_dice()
for j in range(1, 7):
if roll == j:
result_list[j-1] += 1
print(result_list)
if __name__ == '__main__':
main()
[0]*6的值为[0,0,0,0,0,0]
['0' *6]的值为 ['000000']
zip()是将两个列表中的对应元素打包成一个元组,得到的是一个新的列表,列表中每个元素是个元组,不可修改;若果修改则需要转化成字典 dict(zip(l1,l2))
模拟投掷两个筛子:
投掷两个骰子案例:
total_times = 100000
# 初始化列表 [0,0,0,0,0,0,0,0,0,0,0] 记录每个点出现的次数
result_list = [0]*11
roll_list = list(range(2, 13))
# 定义一个字典相关联
roll_dict = dict(zip(roll_list, result_list))
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, x in roll_dict.items():
print('点数:{},次数:{},频率:{}'.format(i, x, x/total_times))