【问题标题】:Dictionary Comprehensions add in a range字典推导在一个范围内添加
【发布时间】:2021-07-25 05:25:33
【问题描述】:

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

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

我要做的是创建一个字典理解,它选择一个随机字典条目并在定义的范围内重复该过程,因此我最终得到一个唯一字典 key.value 对的列表(没有重复)。

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

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

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

我得到的回溯是:

Traceback(最近一次调用最后一次): 文件“/Users/home/Dropbox/Python_general_work/finished_projects/python/Scratch.py​​”,第 38 行,在 random_countries = random.choice(list(d.items()) in range(3)) 文件“/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/random.py”,第 347 行,可选择 返回 seq[self._randbelow(len(seq))] TypeError: 'bool' 类型的对象没有 len()

非常感谢

【问题讨论】:

  • 什么错误?你期待什么结果?使用特定的 rng 种子手动运行这些步骤,以确保我们都在同一页面上。
  • 我最后有一个额外的括号吗?就像您知道的那样,您看起来像是在制作生成器,而不是字典理解。
  • @quamrana 没有多余的吗?最后一个括号是choice()
  • 你想在最终的随机选择中重复吗?
  • @12944qwerty。我理解这个问题,但 OP 有责任让它回答。

标签: python dictionary-comprehension


【解决方案1】:

让我们分解一下你做了什么:

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)]

【讨论】:

  • 太好了,他删除重复项将非常有用。非常感谢。
  • 没问题!但请记住在您的问题中更具体。这次我理解了,不代表下次我也会。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-08
  • 1970-01-01
  • 2014-11-13
相关资源
最近更新 更多