这是目前我的代码。
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, callingpopitem()
raises aKeyError
.
请注意,该方法的随机性实际上来自哈希算法的实现和 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/