0

我几乎做到了,但我的代码不起作用,我不明白为什么:

dice1 = 1
listofallcombinations = []
while dice <= 6:
    dice2 = 1
    while dice2 <= 6:
         listofallcombinations.append((dice1,dice2))
         dice2 = dice2 + 1
    dice1 = dice1 + 1

sumof2dice = []
sumation = 2
while sumation <= 12:
    sumof2dice[str(sumation)] = []
    sumation = sumation + 1

for i in listofallcombinations:
    sumofdice = 2
    while sumofdice <= 12:
        if i[0] + i[1] == sumofdice:
            sumof2dice{str{sumofdice)).append(i)
        sumofdice = sumofdice + 1


for i in sumof2dice
    print i, "\n", sumof2dice[i], "\n"

我得到的错误是:

sumof2dice{str{sumofdice)).append(i)

有语法错误,但我不知道如何修复它。

谢谢!

4

2 回答 2

3

您还可以改进您的代码:

>>> from collections import Counter
>>> listofall = []
>>> for i in range(1,7):
    for j in range(1,7):
        listofall.append(i+j)


>>> Counter(listofall)
Counter({7: 6, 6: 5, 8: 5, 5: 4, 9: 4, 4: 3, 10: 3, 3: 2, 11: 2, 2: 1, 12: 1})

意识到你想要不同的输出,它可以实现如下:

>>> listofall = dict((i, []) for i in range(2,13))
>>> for i in range(1,7):
    for j in range(1,7):
        listofall[i+j].append((i,j))

>>> listofall
{2: [(1, 1)], 3: [(1, 2), (2, 1)], 4: [(1, 3), (2, 2), (3, 1)], 5: [(1, 4), (2, 3), (3, 2), (4, 1)], 6: [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)], 7: [(1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1)], 8: [(2, 6), (3, 5), (4, 4), (5, 3), (6, 2)], 9: [(3, 6), (4, 5), (5, 4), (6, 3)], 10: [(4, 6), (5, 5), (6, 4)], 11: [(5, 6), (6, 5)], 12: [(6, 6)]}
于 2013-11-05T09:17:51.900 回答
1

你可能想要

sumof2dice = {}

而不是一个列表。

我已经修复了代码中的各种语法错误:

dice1 = 1 = []
while dice1 <= 6:
    dice2 = 1
    while dice2 <= 6:
         listofallcombinations.append((dice1,dice2))
         dice2 = dice2 + 1
    dice1 = dice1 + 1

sumof2dice = {}
sumation = 2
while sumation <= 12:
    sumof2dice[str(sumation)] = []
    sumation = sumation + 1

for i in listofallcombinations:
    sumofdice = 2
    while sumofdice <= 12:
        if i[0] + i[1] == sumofdice:
            sumof2dice[str(sumofdice)].append(i)
        sumofdice = sumofdice + 1


for i, s in sumof2dice.items():
    print i, s

输出:

11 [(5, 6), (6, 5)]
10 [(4, 6), (5, 5), (6, 4)]
12 [(6, 6)]
3 [(1, 2), (2, 1)]
2 [(1, 1)]
5 [(1, 4), (2, 3), (3, 2), (4, 1)]
4 [(1, 3), (2, 2), (3, 1)]
7 [(1, 6), (2, 5), (3, 4), (4, 3), (5, 2), (6, 1)]
6 [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]
9 [(3, 6), (4, 5), (5, 4), (6, 3)]
8 [(2, 6), (3, 5), (4, 4), (5, 3), (6, 2)]
于 2013-11-05T09:04:59.373 回答