结合字典

时间:2014-02-07 18:39:26

标签: python list random dictionary

我是一名蟒蛇初学者。如果我想要组合这两个词典,我该怎么办:

dwarf items={'coins':30,'power':11,'Knives':20,'beer':10,'pistol':2}
caves=[('A','B','C','D','E','F','G')]

我想“矮人”随机丢弃任何这些洞穴中的物品

我尝试了zip功能,但没有按照我预期的方式工作。 输出应如下所示:

cache={'A':0,'B':['coins':30],'C':['Knives':20},'D':0,'E':0,'F':0,'G':0}

2 个答案:

答案 0 :(得分:1)

我想你可能正在寻找以下内容:

dwarf_items = {'coins': 30, 'power': 11, 'Knives': 20, 'beer': 10, 'pistol': 2}
caves = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
drop_chance = 0.4  # change this to make it more or less likely an item will drop
cache = {}
for cave in caves:
    if dwarf_items and random.random() < drop_chance:
        item = random.choice(dwarf_items.keys())
        cache[cave] = {item: dwarf_items.pop(item)}
    else:
        cache[cave] = {}

以下是我通过几次运行得到的一些输出示例:

>>> cache
{'A': {}, 'C': {}, 'B': {'Knives': 20}, 'E': {'beer': 10}, 'D': {'power': 11}, 'G': {'coins': 30}, 'F': {}}

>>> cache
{'A': {}, 'C': {'power': 11}, 'B': {'pistol': 2}, 'E': {'Knives': 20}, 'D': {'beer': 10}, 'G': {}, 'F': {'coins': 30}}

>>> cache
{'A': {}, 'C': {}, 'B': {}, 'E': {'beer': 10}, 'D': {}, 'G': {}, 'F': {}}

答案 1 :(得分:0)

这是一个我认为可能接近您正在寻找的解决方案:

import random

cave_names = ['A','B','C','D','E','F','G']
item_names = ['coins', 'power', 'knives', 'beer', 'pistol']

# Create the dictionary of caves, all of which have no items to start
caves = {cave : {item : 0 for item in item_names} for cave in cave_names}

# Randomly distribute the dwarf's items into the caves
dwarf_items = {'coins' : 30, 'power' : 11, 'knives' : 20, 'beer' : 10, 'pistol' : 2}
for key, value in dwarf_items.iteritems():
    for i in range(value):
        # Give away all of the items
        cave = random.choice(cave_names)
        caves[cave][key] += 1
        # Take the item away from the dwarf
        dwarf_items[key] -= 1

print(caves)

以下是在所有矮人的物品随机分配到洞穴之后,洞穴在最后看到的例子:

{'A': {'beer': 2, 'coins': 4, 'knives': 1, 'pistol': 1, 'power': 1},
 'B': {'beer': 0, 'coins': 3, 'knives': 7, 'pistol': 0, 'power': 0},
 'C': {'beer': 1, 'coins': 2, 'knives': 1, 'pistol': 0, 'power': 3},
 'D': {'beer': 3, 'coins': 8, 'knives': 3, 'pistol': 0, 'power': 2},
 'E': {'beer': 2, 'coins': 4, 'knives': 2, 'pistol': 1, 'power': 5},
 'F': {'beer': 2, 'coins': 7, 'knives': 5, 'pistol': 0, 'power': 0},
 'G': {'beer': 0, 'coins': 2, 'knives': 1, 'pistol': 0, 'power': 0}}