在字典中混排特定值(Python 3.5)
问题描述:
我在写一个谋杀案之谜 - 很像Clue。我正在使用字典存储我的所有信息。我的问题:有没有一种方法来混合从一组整数范围中抽取的字典值?我希望每场比赛都能在开始新游戏时在词典中洗牌。现在我专注于角色摆放......我试图找出每场比赛(位置[current_room] [“char”)洗牌角色位置的最佳方式。一旦我明白如何做到这一点,我想要应用此一堆的游戏的其他方面 - 与创建一个全新的神秘解决每场比赛的想法有什么建议欢迎在字典中混排特定值(Python 3.5)
编辑 谢谢你的答案,我并不想。!随机化我的整个字典,只是改变每个游戏中某些键的值,我想我可能需要另一种方式来解决这个问题,当我得到东西时,我会更新这个帖子。改变我想通过编辑词典“洗牌”的特定键的值。位置[1] [“char”] = random.choice([0,1,2]),然后根据random.choice结果中的一系列IF语句更改其他值。再次感谢您的帮助。
locations = {
1: {"name": "bedroom",
"msg": "There is a painting on the wall. \nThe window looks out into the garden.",
"char": 2,
"item": "matches",
"west": 2},
2: {"name": "living room",
"msg" : "The room is freezing cold. The fireplace is empty.",
"char": 1,
"Item": "firewood",
"east": 1},
}
characters = {
1: {"name": "doctor crichton",
"msg": "A tall, handsome archeologist home from a dig in Africa."},
2: {"name": "the widow",
"msg": "An beautiful woman with a deep air of sadness."},
}
current_room = 1
current_char = locations[current_room]["char"]
def status():
"""updates player on info on current room"""
print("You are in the " + locations[current_room]["name"])
char_status()
def char_status():
"""compiles character infomation in current room"""
if current_char > 0:
char_room_info()
else:
print("\nThis room is empty.")
def char_room_info():
"""NPC behavior in each room"""
print(characters[current_char]["name"].title() + " is in the room with you.")
status()
答
Python词典是无序的,所以我不明白你为什么要“洗牌”他们。如果你想在字典中选择随机字符串,也许你可以使用一个列表来包装这个字典,为简单起见。
像这样:
Locations = [ {"name": "bedroom...}, {"name": "livingroom"...},...]
我想你明白了吧。所以现在来访问它们:
Locations[random.rand]["name"]
你也可以使用此:
random.choice(locations.keys())
这是容易得多。
答
如果Python3.x然后执行:
import random
random.choice(list(someDictionary.keys()))
如果Python2.x然后执行:
import random
random.choice(someDictionary.keys())
'进口随机的; random.choice(someDictionary.keys())' –
[如何获得一个随机值在python字典中](http://stackoverflow.com/questions/4859292/how-to-get-a-random-value -in-蟒字典)的 –