字典理解增加了一个范围



我正在制作一个可以在大词典中阅读的程序。它的部分功能是从字典中随机选择一些项目,这是代码的例子:

import random
d = {'VENEZUELA': 'CARACAS', 'CANADA': 'OTTAWA', 'UK': 'LONDON', 'FRANCE': 'PARIS', 'ITALY': 'ROME'}
random_cnty = random.choice(list(d.items())
print(random_cnty)

我想做的是创建一个字典理解,它选择一个随机的字典条目,并在定义的范围内重复这个过程,这样我就得到了一个唯一的字典关键字-值对列表(没有重复(。

我尝试了以下操作,但出现语法错误:

random_countries = random.choice(list(d.items()) for i  in range(3))

一个范围和一个随机函数可以同时添加到字典理解中吗?

我得到的回溯是:

追踪(最近一次通话(:文件"/Users/home/Dropbox/Python_general_work/finished_projects/Python/Scratch.py";,第38行,inrandom_countries=random.cachoice(范围(3(中的列表(d.items((((文件"/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/random.py";,347行,可选return seq[self.randbelow(len(seq((]TypeError:"bool"类型的对象没有len((

非常感谢

让我们来分析一下您所做的:

random.choice(list(d.items()) for i  in range(3))
# To
temp_ = []
for i in range(3):
temp_.append(d.items())
random.choice(temp_)

您制作的代码将为我们提供3份d.items()的随机选择

为了让你从d.items()中获得多个随机选择(我假设这是你的问题(,你可以做:

choices = []
for i in range(3):
choices.append(random.choice(list(d.items())))
# Or, to avoid duplicates
choices = []
temp = list(d.items()) # Make temp variable so you avoid mutation of original dictionary.
for i in range(3):
choices.append(temp.pop(random.randint(0,len(temp)-(i+1))))

如果你想通过理解做到这一点:

choices = [random.choice(list(d.items())) for i in range(3)] # This is different than your code because it takes a random choice of `d` 3 times instead of taking a choice from three copies.
# Or to avoid duplicates
temp = list(d.items()) # You don't need this, but it's better to keep it here unless you won't need the original dictionary ever again in the program
choices = [temp.pop(random.randint(0,len(temp)-(i+1))) for i in range(3)]

最新更新