我正在尝试用 Python 进行闪存卡测验挑战。这涉及从文本文件中获取州及其首府。我已经成功地进行剥离和拆分,以便创建带有键的字典。
但是每次我在 for 循环中使用随机选择时,它都会输出最后一个键(例如怀俄明州),另一方面,当我将其从 for 循环中取出时,它只输出第一个键(例如阿拉巴马州)
这是它的样子(显然这不显示文本文件)
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: ")
最佳答案
问题是 while
循环位于 for
循环的范围内,因此您永远没有机会填充字典。但是,将 while
循环移到 for
循环之外并不能解决不同的问题;您在 for
循环中初始化 d
,以便它不断重置回空字典,删除所有以前的条目。
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
关于python - python 文件上的随机选择不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41283074/