实现说明
tallies、counts、safe 定义在模块顶层,中间不经过函数作用域。
使用要点
- 每一步打印都带着自己的标签:
tallies:、True == 1:、hash equal:。
常见问题
这份代码可以原样复制进项目使用吗?
可以。粘进去就能运行,中间没有包管理器的事。 文件用顶层绑定保存自己的状态:tallies、counts、safe。
核心语句
tallies[True] = "bool entry"
tallies[1] = "int entry"
print("tallies:", tallies)
print("True == 1:", True == 1)
print("hash equal:", hash(True) == hash(1))
# 1.0 maps to the same key slot as well
counts = {1: "one"}
safe = {"true": [], "1": []}
tallies = {}
代码示例
tallies = {}
# True equals 1 and hashes identically, so both occupy one key slot; the later write wins
tallies[True] = "bool entry"
tallies[1] = "int entry"
print("tallies:", tallies)
print("True == 1:", True == 1)
print("hash equal:", hash(True) == hash(1))
# 1.0 maps to the same key slot as well
counts = {1: "one"}
counts[1.0] = "float one"
counts[True] = "flag"
print("counts:", counts)
# when the source type matters, normalize keys to strings first
safe = {"true": [], "1": []}
safe["true"].append("x")
print("safe:", safe)