计算三个骰子掷骰的频率

时间:2019-01-07 16:53:17

标签: python

我需要创建一个6 x 6 x 6的表格,其中包含所有216种可能的三个骰子结果。考虑到相同的骰子值以任何顺序出现都是相同的结果(例如(1,4,6)与所有1,4,6转换相同,即(6,4,1)或(4,6 ,1),等等。

然后我要计算不同结果的频率并打印出来 按发生率的高低排序。(也许带字典?)

我列出了此列表:

mylist = [[[(x,y,z) for z in range (1,7)]for y in range(1,7)]for x in range (1,7)]

我有216种可能的结果。

但是我无法使它们计数并找到相同的结果...

你能帮我吗?

3 个答案:

答案 0 :(得分:1)

我认为您在这种情况下不必使用3维表,我会按照以下方式进行操作

mylist = []
for x in range(1,7):
    for y in range(1,7):
        for z in range(1,7):
            mylist.append((x,y,z))
mylist = [tuple(sorted(i)) for i in mylist]
for i in list(set(mylist)):
    print(i,'occurs',mylist.count(i),'times')

答案 1 :(得分:0)

您可以使用itertools.product产生3个骰子产生的所有可能结果,将结果传递给collections.Counter,然后传递给frozenset来计算结果的组成,而忽略顺序,然后使用Counter.elements()方法将计数重新构造为可读的元组,作为dict理解中的键:

from itertools import product
from collections import Counter
{tuple(sorted(Counter(dict(t)).elements())): c for t, c in Counter(frozenset(Counter(p).items()) for p in product(range(1, 7), repeat=3)).items()}

这将返回:

{(1, 1, 1): 1,
 (1, 1, 2): 3,
 (1, 1, 3): 3,
 (1, 1, 4): 3,
 (1, 1, 5): 3,
 (1, 1, 6): 3,
 (1, 2, 2): 3,
 (1, 2, 3): 6,
 (1, 2, 4): 6,
 (1, 2, 5): 6,
 (1, 2, 6): 6,
 (1, 3, 3): 3,
 (1, 3, 4): 6,
 (1, 3, 5): 6,
 (1, 3, 6): 6,
 (1, 4, 4): 3,
 (1, 4, 5): 6,
 (1, 4, 6): 6,
 (1, 5, 5): 3,
 (1, 5, 6): 6,
 (1, 6, 6): 3,
 (2, 2, 2): 1,
 (2, 2, 3): 3,
 (2, 2, 4): 3,
 (2, 2, 5): 3,
 (2, 2, 6): 3,
 (2, 3, 3): 3,
 (2, 3, 4): 6,
 (2, 3, 5): 6,
 (2, 3, 6): 6,
 (2, 4, 4): 3,
 (2, 4, 5): 6,
 (2, 4, 6): 6,
 (2, 5, 5): 3,
 (2, 5, 6): 6,
 (2, 6, 6): 3,
 (3, 3, 3): 1,
 (3, 3, 4): 3,
 (3, 3, 5): 3,
 (3, 3, 6): 3,
 (3, 4, 4): 3,
 (3, 4, 5): 6,
 (3, 4, 6): 6,
 (3, 5, 5): 3,
 (3, 5, 6): 6,
 (3, 6, 6): 3,
 (4, 4, 4): 1,
 (4, 4, 5): 3,
 (4, 4, 6): 3,
 (4, 5, 5): 3,
 (4, 5, 6): 6,
 (4, 6, 6): 3,
 (5, 5, 5): 1,
 (5, 5, 6): 3,
 (5, 6, 6): 3,
 (6, 6, 6): 1}

答案 2 :(得分:0)

一种使用我提到的东西做到这一点的方法:

from collections import Counter

a = [(i,j,k) for i in range(1, 7) for j in range(1, 7) for k in range(1, 7)]
c = Counter(frozenset(x) for x in a if len(set(x)) == 3)

counter_most_common = c.most_common(1)[0][1]
for combination, counter in c.items():
    if counter == counter_most_common:
        print(f"{combination} is one of the most common combinations! It exists {counter} times")

如您所见,它们都是一样的可能性,如果您考虑一下,这是非常合理的

相关问题