合并词典

2024-06-16 15:27:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python初学者。如果我想合并这样两个词典,我该怎么办:

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

我想让“侏儒”在这些洞穴里随便扔东西

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

^{pr2}$

Tags: 功能方式items词典powerdwarf初学者coins
2条回答

我想你可能在找以下的东西:

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] = {}

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

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

^{4}$

这里有一个解决方案,我认为它可能与您想要的很接近:

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)

下面是一个例子,在矮人的所有物品被随机分配到洞穴之后,洞穴最终会看到什么:

^{pr2}$

相关问题 更多 >