实现说明
各个操作都建立在顶层绑定之上:spend、signups。
使用要点
- 演示输出是带标签的(
slope=、predict at 35 ->、correlation=),每个操作都会留下自己的一行标注。
常见问题
除了语言工具链还要下载什么吗?
除了这个语言的工具链,什么都不用再下载。 全部导入都来自标准库:statistics。 跨调用保留的状态放在这些顶层绑定里:spend、signups。
代码示例
from statistics import linear_regression, correlation
# Weekly ad spend (x) versus signups (y): a textbook linear relationship.
spend = [10, 20, 30, 40, 50]
signups = [12, 21, 32, 38, 51]
slope, intercept = linear_regression(spend, signups)
print(f"slope={slope:.3f} intercept={intercept:.3f}")
print(f"predict at 35 -> {intercept + slope * 35:.1f}")
# correlation quantifies how linear the relationship is, from -1 to 1.
r = correlation(spend, signups)
print(f"correlation={r:.4f}")
print(f"r squared={r ** 2:.4f}")
# xs and ys must have equal length; xs need not be sorted.