2014-02-07 57 views
1

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

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

我想“侏儒”随机丢弃的物品在这些洞穴

我尝试了拉链的功能,但没有奏效我期待的方式。 输出应该是这样的:

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

洞穴不是一本字典。这里有很多语法错误。 –

回答

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': {}} 
+0

如果只是把一个混合的洞穴副本分别放入这个列表中,会更好吗? – akaRem

+0

这些代码确实对我有效,您使用的是哪个版本? – Kunlin

+0

您可能需要将'import random'添加到代码的顶部。这是Python 2.7,但它也应该在其他版本中工作。 –

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

这一个没有工作,错误信息是'字典'没有'iteritems'的属性 – Kunlin

+0

@ user3285116然后你必须在Python 3上。 iteritems()被重命名为items() –