我解决问题的方法如下 -
a=[ ]
for i in range(7):
a.append([0]*7)
c=dict()
for i in range(7):
for j in range(7):
a[i][j]=(i,j)
for i in range(7):
for j in range(7):
c[i+j]=tuple((i*j+j+c))
print c
但这会产生:
{0: (0, 0), 1: (1, 0), 2: (2, 0), 3: (3, 0), 4: (4, 0), 5: (5, 0), 6: (6, 0), 7: (6, 1), 8: (6, 2), 9: (6, 3), 10: (6, 4), 11: (6, 5), 12: (6, 6)}
答案 0 :(得分:2)
这样做的一步一步是
pairs = {}
for first in range(1,7):
for second in range(1,7):
total = first + second
if total in pairs:
# If sum exists, add this tuple to the list for this key.
pairs[total] += [(first,second)]
else:
# If sum doesn't exist, start a new list for this key
pairs[total] = [(first,second)]
结果
>>> pairs
{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)]}
由于这听起来像学术练习,我假设你不能使用一些预先存在的Python模块。否则,您可能需要查看collections.defaultdict和itertools.product。前者可以处理"这个密钥是否存在?"后者可以处理组合以删除嵌套的for
循环。
答案 1 :(得分:1)
这将有效:
combinations = {}
for a in range(1, 7):
for b in range(1, 7):
combinations.setdefault(a+b, []).append((a, b))
结果:
{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)],
}
答案 2 :(得分:0)
使用一些标准的Python实用程序:
from collections import defaultdict
from itertools import product
单个骰子上的所有数字:
numbers = range(1,7)
现在,对于每个组合,将组合求和并将组合附加到该组合的列表中:
reduce(lambda acc, comb: acc[sum(comb)].append(comb) or acc, product(numbers, numbers), defaultdict(list))
导致:
defaultdict(<type 'list'>, {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)]})