【问题标题】:Python how to choose randomly from a dict [duplicate]Python如何从字典中随机选择[重复]
【发布时间】:2013-09-16 18:07:31
【问题描述】:
{"raitisu": [{"name": "test"}, {"name": "test1"}]}         
note = {'name': ""+random.choice(notes.keys())+""}

如何在test和test1之间随机选择?

【问题讨论】:

标签: random python-3.x choice


【解决方案1】:

notes 中随机选择一个字典列表(使用字典在被视为可迭代时产生其键的事实),然后使用已知键“名称”从列表中选择一个值。

import random
notes = {"raitisu": [{"name": "test"}, {"name": "test1"}],
         "iceyyheart": [{"name": "test"}]}
notes_key = random.choice(notes)
random_dict_list = notes[notes_key]
random_value = random.choice(random_dict_list)["name"]
note = { 'name': random_value }

【讨论】:

  • 非常感谢,但如果是这样的话,字典的名称与它们的项目 {"raitisu": [{"name": "test"}, {"name": "test1" }],"iceyyheart": [{"name": "test"}]} 是正确的,比如 note = { 'name': random.choice( notes["random.name?"] )["name"] }
  • 嗯,就像你说的那样为每个 raitisu、iceyyheart 等(用户名列表)选择一个随机值,我有另一个代码可以向其他用户名发送注释,我不知道如何随机选择在“用户”值之间,加载它然后通过执行命令自动删除它
  • 非常感谢,但这会选择一个随机用户,然后是一个随机项目/注释,我怎样才能让它不是随机用户,而是像“+user.name.lower()”这样调用 cmd 的用户+"
  • 您在原始问题中是否还有其他限制?
  • 导入随机名称 = user.name.lower() notes = {"raitisu": [{"name": "test"}, {"name": "test1"}], "iceyyheart ": [{"name": "test"}]} random_note = random.choice(notes[name]) ####### 会起作用吗?
猜你喜欢
  • 1970-01-01
  • 2015-05-25
  • 2016-04-14
  • 2019-05-05
  • 1970-01-01
  • 2016-09-06
  • 1970-01-01
  • 2015-01-09
  • 1970-01-01
相关资源
最近更新 更多