gpt4 book ai didi

python - 如何让字典打印出随机键

转载 作者:太空宇宙 更新时间:2023-11-04 00:26:34 25 4
gpt4 key购买 nike

file = open(selection, 'r')
dictionary = {}
with file as f:
for line in f:
items = line.split(',')
key, values = items[0], items[1:]
dictionary[key] = values

n= int(input("How many words would you like to be tested on: "))
while n > length:
print("Invalid. There are only" ,length, "entries")
n= int(input("How many words would you like to be tested on: "))
print("You have chosen to be tested on",n, "words.\n")


for i in range(n):
while len(dictionary)>0:
choice = random.shuffle(list(dictionary.keys()))
correctAnswer = dictionary.get(choice)
print("English: ",choice)
answer = input("Spanish: ")
if answer.lower() == correctAnswer:
print("Correct!\n")
del dictionary[choice]
else:
print("Incorrect")
wrongAnswers.append(choice)
break
print("\nYou missed", len(wrongAnswers), "words\n")

你好,我正在尝试在 python 上创建一个词汇测试,但是当我运行代码时,它没有打印出 key ,而是打印出“无”如何让代码打印出随 secret 钥?

最佳答案

您可以使用 random.choice 而不是 shuffle。

choice = random.choice(list(dictionary.keys()))

shuffle 会更改您发送到函数中的列表,并且由于您没有保存对该列表的引用,所以您什么也得不到。此外,它只生成该列表的混洗版本,而不是单个值。

alist = [1,2,3,4,5,6]
random.shuffle(alist)
print(alist)

>> [2, 5, 6, 4, 3, 1]

关于python - 如何让字典打印出随机键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47252852/

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