gpt4 book ai didi

python - 访问列表时的语法错误

转载 作者:行者123 更新时间:2023-12-03 08:15:49 25 4
gpt4 key购买 nike

我几乎完成了此操作,但是我的代码无法正常工作,我也不明白为什么:

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)

有语法错误,但我不知道如何解决。

谢谢!

最佳答案

你可能想要

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

关于python - 访问列表时的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19785101/

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