为了账号安全,请及时绑定邮箱和手机立即绑定

为具有 1 个值或 0 的列表的列表计算 st.dev 和均值

为具有 1 个值或 0 的列表的列表计算 st.dev 和均值

茅侃侃 2022-11-29 15:31:30
我有这个列表列表:fall_2_gpa = [[4.0, 3.4175, 3.1675, 3.2475, 3.25, 3.2475, 3.3325, 3.585, 3.5825, 3.3325, 3.5, 3.585, 3.8325, 3.165, 3.5025, 3.835, 3.5, 3.4175, 3.6675, 3.165, 3.25, 3.4175, 3.9175, 3.6675, 3.8325, 3.2475, 3.4175, 3.4175, 3.5825, 3.415, 3.5825, 3.585, 3.25, 3.4175, 3.6675, 3.3325, 3.5, 3.165, 3.3325, 3.6675, 3.6675], [3.5], [3.1675, 3.4175, 3.5, 3.6675, 2.5, 2.835, 3.585, 3.4175, 3.25, 3.4175, 3.1675, 3.75], [2.6675, 3.0], [3.0825, 3.665, 3.6675, 3.3325, 3.3325, 3.415], [3.3325, 3.415, 3.415, 3.415, 3.75, 3.75, 3.665, 3.6675, 3.6675, 3.5825, 3.5825, 3.9175, 3.4175, 3.6675, 3.5, 3.5825, 3.585, 3.6675, 3.665, 3.4175, 3.585, 3.4175, 3.415, 3.75, 4.0, 3.5, 3.6675, 3.25, 3.585, 3.3325, 3.4175, 3.5, 3.6675, 3.7525, 3.3325, 3.835, 3.335, 3.665, 3.5, 3.6675, 3.585, 3.75, 3.75, 3.5, 3.415, 3.0825, 3.6675, 3.2475, 3.2475, 3.335, 3.9175, 3.75, 3.75, 3.75, 3.585, 3.585, 3.4175, 3.25, 3.3325, 3.5, 3.25, 3.75, 2.835, 3.1675, 2.5825, 3.25, 3.5825, 2.915, 2.8325, 2.5, 3.0825, 3.3325, 2.8325, 3.25, 2.8325, 3.335], [3.5, 3.3325, 3.6675], [3.165, 3.4175, 3.4975, 3.25], [3.5825, 3.5, 3.4175, 3.75, 3.335, 3.335, 3.415, 3.5, 3.6675, 3.165, 3.6675, 3.4975, 3.9175, 3.6675, 3.4175, 3.25, 3.3325, 3.585, 3.835, 3.2475, 3.335, 3.75, 3.5825, 3.5, 3.4175, 3.5, 3.75, 3.5825, 3.585, 3.335, 3.5825, 3.5825, 3.3325, 3.75, 3.5, 3.6675, 3.3325, 3.5825, 3.4175, 3.415, 3.585, 3.75, 3.415, 3.4175, 3.25, 3.4175, 3.415, 3.415, 3.75, 3.9175, 3.8325, 3mean_fall_2 = [statistics.mean(d) for d in fall_2_gpa if d != 0] stdev_fall_2 = [statistics.stdev(d) for d in fall_2_gpa if d != 0]但我不断收到此错误:statistics.StatisticsError:方差至少需要两个数据点我相信我得到这个是因为一些子列表只有 1 个值并且不超过 2 个。对于另一个列表我得到这个错误:statistics.StatisticsError: mean 至少需要一个数据点这可能意味着它找到了一个空的子列表?有办法解决这些问题吗?我需要 st.dev 并且意味着要计算所有内容,无一例外。
查看完整描述

1 回答

?
守候你守候我

TA贡献1802条经验 获得超10个赞

fall_2_gpa 列表包含一些大小为 1 的列表,这些列表将传递给 statistics.stdev() 函数。但是,statistics.stdev() 期望参数至少有两个项目。因此,我们可以在处理列表项时添加一个条件来检查列表的大小:-

stdev_fall_2 = [statistics.stdev(d) for d in fall_2_gpa if d != 0 and len(d)>1]

以类似的方式,我们也可以指示函数在列表大小小于 2 时使用一些默认值。

使用以下内容在 else 条件下添加 0:

stdev_fall_2 = [statistics.stdev(d) if d != 0 and len(d) > 1 else 0 for d in fall_2_gpa]


查看完整回答
反对 回复 2022-11-29
  • 1 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信