【问题标题】:Combine dictionary结合字典
【发布时间】:2014-02-07 18:39:25
【问题描述】:

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

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}

【问题讨论】:

  • Caves 不是字典。这里有很多语法错误。

标签: python list random dictionary


【解决方案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': {}}

【讨论】:

  • 最好只是获得一个随机的洞穴副本并将项目分别放入该列表中吗?
  • 这些代码对我有用,你用的是什么版本?
  • 您可能需要在代码顶部添加import random。这是 Python 2.7,但它应该也可以在其他版本中使用。
【解决方案2】:

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

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}}

【讨论】:

  • 这个不行,错误信息是'dict' has no attribute to 'iteritems'
  • @user3285116 你必须在 Python 3 上。 iteritems() 被重命名为 items()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-23
  • 2018-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-25
  • 2016-04-26
相关资源
最近更新 更多