You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将列表元素转换为百分比?掷骰子结果的数量与占比统计需求

统计骰子点数的出现次数与占比

实现方案

可以借助Python标准库的collections.Counter快速完成计数,再基于总投掷次数计算占比,以下是完整实现:

import random
from collections import Counter

# 你原有的骰子投掷代码(可根据实际修改dice_amount和dice_face的值)
dice_amount = 100
dice_face = 6
dice_rolls = []
for i in range(dice_amount):
    dice_rolls.append(random.randint(1, dice_face))

# 统计每个点数的出现次数
counts = Counter(dice_rolls)

# 计算并输出每个点数的出现次数与占比
total_rolls = dice_amount
print("统计结果:")
# 按点数从小到大排序输出
for num in sorted(counts):
    count = counts[num]
    percentage = (count / total_rolls) * 100
    print(f"数字{num}出现{count}次,占比{percentage:.2f}%")

关键说明

  • Counter(dice_rolls):自动遍历列表并统计每个元素的出现次数,返回一个键为点数、值为对应次数的字典
  • sorted(counts):确保输出的点数按升序排列,避免结果杂乱
  • percentage:.2f:将百分比保留两位小数,提升结果可读性

内容的提问来源于stack exchange,提问作者Samuel Molero Badia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 04:25:32