gpt4 book ai didi

python - 令人困惑的任务

转载 作者:行者123 更新时间:2023-11-30 23:15:03 26 4
gpt4 key购买 nike

我解决这个问题的方法如下-

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)}

最佳答案

一步一步地做到这一点是

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.defaultdictitertools.product 。前者可以处理“这个 key 是否存在?”后者可以处理组合以删除嵌套的 for 循环。

关于python - 令人困惑的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28456021/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com