Python随机数频率字典
我试图让一个函数生成两个随机整数,范围从1到6。并具有两个整数值之和的频率字典 它用于模拟两个骰子滚动x的次数 这是我的代码和我的代码:Python随机数频率字典,python,dictionary,Python,Dictionary,我试图让一个函数生成两个随机整数,范围从1到6。并具有两个整数值之和的频率字典 它用于模拟两个骰子滚动x的次数 这是我的代码和我的代码: def sim(): dictionary = {} loop_value = 0 total = 0 while loop_value < 10: num_1 = random.randint(1, 6) num_2 = random.randint(1, 6) tot
def sim():
dictionary = {}
loop_value = 0
total = 0
while loop_value < 10:
num_1 = random.randint(1, 6)
num_2 = random.randint(1, 6)
total = total + num_1 + num_2
if value in dictionary:
dictionary[total] += 1
else:
dictionary[total] = 1
loop_value += 1
print("Loop value", str(loop_value))
print(dictionary)
def sim():
字典={}
循环_值=0
总数=0
当回路_值<10时:
num_1=random.randint(1,6)
num_2=random.randint(1,6)
总计=总计+数量1+数量2
如果字典中有值:
字典[总数]+=1
其他:
字典[总数]=1
循环_值+=1
打印(“循环值”,str(循环值))
印刷(字典)
这段代码只是将所有值相加。因此,并非每个值都是唯一的。如何解决此问题?替换此问题
if value in dictionary:
dictionary[total] += 1
与
我不确定您从哪里获得
值
(它在您的代码中没有定义),但几乎可以肯定,它会导致您的else
语句不断执行。虽然Martins answer可能会解决您的问题,但您可以使用更灵活的方法进行计数
下面是一个简单的例子:
>>> from collections import Counter
>>> Counter(random.randint(1, 6) + random.randint(1, 6) for x in range(10))
Counter({3: 3, 6: 3, 5: 2, 10: 1, 7: 1})
计数器是字典,因此您可以用同样的方法操作它们
total = total + num_1 + num_2
我认为您不应该在此处添加total
,只需:
total = num_1 + num_2
另外,将另一篇文章中提到的value
替换为total
if total in dictionary:
dictionary[total] += 1
else:
dictionary[total] = 1
以下是您需要的:
def sim(loop_value):
dictionary = {}
total = 0
for i in xrange(loop_value):
num_1 = random.randint(1, 6)
num_2 = random.randint(1, 6)
total += num_1 + num_2
if total in dictionary:
dictionary[total] += 1
else:
dictionary.setdefault(total, 1)
total = 0
print("Loop value", str(loop_value))
print(dictionary)
>>> sim(5)
>>> ('Loop value', '5')
{4: 1}
('Loop value', '5')
{4: 1, 7: 1}
('Loop value', '5')
{11: 1, 4: 1, 7: 1}
('Loop value', '5')
{8: 1, 11: 1, 4: 1, 7: 1}
('Loop value', '5')
{8: 1, 11: 1, 4: 1, 7: 2}
我们能看到一些预期的输出吗?
如果字典中的值定义了“值”?
def sim(loop_value):
dictionary = {}
total = 0
for i in xrange(loop_value):
num_1 = random.randint(1, 6)
num_2 = random.randint(1, 6)
total += num_1 + num_2
if total in dictionary:
dictionary[total] += 1
else:
dictionary.setdefault(total, 1)
total = 0
print("Loop value", str(loop_value))
print(dictionary)
>>> sim(5)
>>> ('Loop value', '5')
{4: 1}
('Loop value', '5')
{4: 1, 7: 1}
('Loop value', '5')
{11: 1, 4: 1, 7: 1}
('Loop value', '5')
{8: 1, 11: 1, 4: 1, 7: 1}
('Loop value', '5')
{8: 1, 11: 1, 4: 1, 7: 2}