【发布时间】:2021-08-24 19:03:44
【问题描述】:
我正在尝试使用 random.choices 模拟离散值的均匀分布。每次生成新集合时,表示唯一计数的键都会递增。
为什么([2,2]) 比[1,3] 更不可能发生统一结果?
def sim_counts(size, values=[1,-1], popsize=2):
count_dict = {}
for i in range(popsize):
X = random.choices(values,k=size)
_, counts = np.unique(X, return_counts=True)
if len(counts) == 1:
counts = [0,counts[0]]
key = str(np.sort(counts))
if key not in count_dict:
count_dict[key] = 0
count_dict[key] +=1
else:
count_dict[key] +=1
return count_dict
sim_counts(4, values=[1,-1], popsize=10000)
>>> {'[2 2]': 3747, '[0 4]': 1319, '[1 3]': 4934}
【问题讨论】:
-
设置
key = str(counts)而不是key = str(numpy.sort(counts))你会明白为什么:-) -
天哪!谢谢
-
此外,如果您执行“从集合导入 defaultdict”然后设置 count_dict = defaultdict(int),此代码会更简洁。然后你可以在没有 if/else 语句的情况下执行 count_dict[key] += 1。
-
@JonSG,如果你把它写成答案,我会接受。
-
@user2263572 或使用
Counter
标签: python random statistics