我差不多完成了这个,但是我的代码无效,我不明白为什么:
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)
有语法错误,但我不知道如何修复它。
谢谢!
答案 0 :(得分: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)]}
答案 1 :(得分: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)]