python-3.x - 你如何获得从字典中随机选择的值

标签 python-3.x

这是目前我的代码。

if Pokémon == 'Charmander':
    selectyourmove = input('Select your move: Flamethrower, Fire Fang, 
Scratch or Ember: ')#select your move
    if selectyourmove == 'Flamethrower':
        numberchoosing1 = random.randint(20, 22)#randomly decides 
damage of the chosen move in the range
        print(choice, 'has lost' ,numberchoosing1, 'health out of its' 
,HP, 'health!')

我的字典很简单。它是:

HP = {'Char':'60', 'Squir':'50', 'Pika':'80', 'Eve':'50', 'Bulb':'70', 'Clef':'100'}

所有这些都已定义。

如何获取从字典中随机选择的值

最佳答案

第一种方法是使用 dict.popitem :

Remove and return an arbitrary (key, value) pair from the dictionary. popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError.

请注意,该方法的随机性实际上来自哈希算法的实现和 python dict 元素布局。这比随机性更晦涩。

第二种方式,真正的“随机”方式,是使用 random.choice .它不会修改字典,而是在提供给它的列表中选择随机索引:

import random
hp = {'Char':'60', 'Squir':'50', 'Pika':'80', 'Eve':'50', 'Bulb':'70', 'Clef':'100'}
print(random.choice(list(hp.keys())))

工作原理说明:

>>> random.choice(list(HP.keys()))
'Pika'
>>> random.choice(list(HP.keys()))
'Clef'
>>> random.choice(list(HP.keys()))
'Pika'

这里的列表是从 .keys() 构造的,但是当你需要对时(比如来自 popitem())你可以使用 .items() :

>>> random.choice(list(HP.items()))
('Clef', '100')
>>> random.choice(list(HP.items()))
('Pika', '80')
>>> random.choice(list(HP.items()))
('Char', '60')

同样,当然 .values() 将只生成 dict 项的右侧元素,因此不会给您带来太多满足感.keys().items() 可以。

PS:那如果你需要重现prev。运行,您可以使用 random.seed 修复“随机性”

关于python-3.x - 你如何获得从字典中随机选择的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47105975/

相关文章:

python : Using Decorators to write Logs on a file

python - 如何使用漂亮的汤从 html 文档中获取 <text> 标签

python - 埃拉托斯特尼筛法遗漏了一些复合 Material

python - 未实现错误: X is not picklable

regex - 如何减少python正则表达式中的步骤?

python-3.x - 如何在 Windows 上安装 setproctitle?

python-3.x - 在我的二分搜索算法中,Python 在列表中找不到 0 个索引成员

sockets - Python错误: Can't convert bytes to string implicitly

python - 尝试使用 Python 3.7.2 和 IMAPClient 批量删除电子邮件 - imaplib.IMAP4.error : UID command error: BAD [b'Command line too large']

python - 在 Python3 ubuntu 上安装 tkinter