python - python 文件上的随机选择不起作用

标签 python

我正在尝试用 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/

相关文章:

python - 将空字典作为关键字参数传递总是安全的吗?

python - 制作Python 2.7模块: Referencing values?

python - 我的循环正在努力将字符串的第一个字符移动到打印中字符串的末尾以获取字符串的长度

python - 获取字符串的unicode字符

python - 在 nitrousio 中安装 python 包

python - Jinja2 扩展多个关键字参数

python - 登录 csv 文件的正确方法是什么?

python - 使用 hmac 生成瑞典 BankID Python 动画 QR 代码

java - 如何在 Python 列表中实现前后递增?

python - UDP广播编程