我正在尝试用Python进行闪存卡测验挑战。这涉及从文本文件中获取州和它们的首都。我设法剥离并拆分以创建带键的字典。
但每次我在for循环中使用随机选择它输出最后一个键(例如怀俄明州)另一方面,当我把它从for循环中取出时,它只输出第一个键(例如Alabama)
这是它的样子(显然这不显示文本文件)
import random
with open("state_capitals.txt","r") as f:
for line in f:
cleanedLine = line.strip().split(',')
state = cleanedLine[0]
capital = cleanedLine[1]
d = {}
d[state] = capital
while len(d)>0:
choice = random.choice(list(d.keys()))
print("What is the capital city of",choice,"?")
answer=input("Answer: ")
答案 0 :(得分:1)
问题是你在while
循环范围内有for
循环,所以你永远不会有机会填充你的字典。但是,将while
循环移到for
循环之外并不能解决另一个问题;您在 d
循环中初始化for
,以便不断重置为空字典,删除所有以前的条目。
import random
d = {} # Create the dict once, otherwise each loop will delete all previous entries
with open("state_capitals.txt","r") as f:
for line in f:
cleanedLine = line.strip().split(',')
state = cleanedLine[0]
capital = cleanedLine[1]
d[state] = capital
# Move this outside the while loop. There's no need to recreate it on every iteration
states = list(d.keys())
# Move the while loop to be outside of the for loop
while len(d)>0:
choice = random.choice(states)
print("What is the capital city of",choice,"?")
answer=input("Answer: ")
# Allow the user to type Quit/quit to break the loop
if answer.lower() == 'quit':
break
答案 1 :(得分:0)
您的for
位于choice = random.choice(list(d.keys()))
循环内,因此在for
期间,词典只有一个密钥。您还可以在每个min
循环迭代中重新初始化字典。