我正在建立一个投票系统来挑选一支球队,但我已经碰壁了。代码工作正常,直到decision2
。有什么想法吗?
请记住此代码是一项正在进行的工作。
teamNames = []
teams = {}
easy = [0, 1, 2, 3, 4, 5]
NoVotes1 = {'first' : 0, 'second' : 0, 'third' : 0, 'fourth' : 0, 'fifth' : 0}
NoVotes2 = {'first' : 0, 'second' : 0, 'third' : 0, 'fourth' : 0, 'fifth' : 0}
NoVotes3 = {'first' : 0, 'second' : 0, 'third' : 0, 'fourth' : 0, 'fifth' : 0}
NoVotes4 = {'first' : 0, 'second' : 0, 'third' : 0, 'fourth' : 0, 'fifth' : 0}
NoVotes5 = {'first' : 0, 'second' : 0, 'third' : 0, 'fourth' : 0, 'fifth' : 0}
while True:
print("Enter team name " + str(len(teamNames) + 1) + (" or press enter to stop."))
name = input()
if name == "":
break
teamNames = teamNames + [name]
print("The team names are ")
for name in teamNames:
print(" " + name)
for name in teamNames:
teams[name] = 0
teamNames.sort()
print("In alphabetical order the team names are ")
print()
print(str(teamNames))
y = 0
decision1 = input("Would you like to enter a vote? (1 = yes, 2 = no)")
while decision1 == "1":
print("ok great, where did " + teamNames[y] + " come")
decision2 = input()
if decision2 == "1":
teams[easy[y]] = teams[easy[y]] + 1
y = y + 1
if decision1 == "2":
break
elif n == "6":
break
答案 0 :(得分:0)
我想我看到你误解了什么。与列表不同,标准词典没有顺序概念或第n个(例如第一个)项目。它们只是键和值之间的关联。当您说teams[key] = value
时,您设置的值为key
,当您说value = teams[key]
时,您的值为key
。可能key
是一个数字,但它不一定是,如果key
为1那么这并不意味着字典中的第二个值,或第一个或任何其他位置。也许这个示例交互式会话将帮助您理解:
>>> dictionary = {"a": "b", "c": "d"}
>>> dictionary = {"a": "b", "c": "d", 5: "e"}
>>> dictionary[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 1
>>> dictionary["c"]
'd'
>>> dictionary[5]
'e'
你想要的是teams[teamNames[y]] = teams[teamNames[y]] + 1
,顺便说一下,它可以缩短为teams[teamNames[y]] += 1
。
这一切都有意义吗?如果不是,我建议用字典做一些简单的实验,直到你更好地理解它们。在shell中玩。使用词典编写一些小程序来查看它们的作用。