之前“缩短”你的代码,以确保它是正确的。目前inv.update
只会覆盖条目!
我会建议使用的Counter
而不是dict
,因为它已经实现了你想要的逻辑:
>>> from collections import Counter
>>> inv = Counter({'arrow': 12, 'gold coin': 42, 'rope': 2, 'torch': 4, 'dagger': 1})
>>> dragon = Counter({'gold coin': 50, 'ruby': 15})
>>> inv.update(dragon)
>>> inv
Counter({'arrow': 12,
'dagger': 1,
'gold coin': 92, # the 42 and 50 are added!
'rope': 2,
'ruby': 15,
'torch': 4})
您使用的唯一功能是show_inv
。然而这个函数的唯一目的是为了表示该对象,没有太多可以“缩短”的地方。这似乎是正确的。
但是,如果你有一个“对象”(在dict
)和该对象的功能,你应该考虑使用“类”来包装它。有迹象表明,允许您自定义的“弦” - 表示方法:__str__
和__repr__
等等这些可以用来代替一个明确的函数(或方法)调用的:
from collections import Counter
class Inventory(Counter): # subclass Counter
def __str__(self): # overwrite the str-representation (this method is used by "print")
content = ['{} {}'.format(name, cnt) for name, cnt in self.items()]
content.insert(0, 'inventory:')
content.append('total number of items: {}'.format(sum(self.values())))
return '\n'.join(content)
inv = Inventory({'arrow': 12, 'gold coin': 42, 'rope': 2, 'torch': 4, 'dagger': 1})
print(inv)
# inventory:
# arrow 12
# gold coin 42
# dagger 1
# rope 2
# torch 4
# total number of items: 61
dragon = {'gold coin': 50, 'ruby': 15}
inv.update(dragon)
print(inv)
# inventory:
# ruby 15
# gold coin 92
# dagger 1
# rope 2
# torch 4
# arrow 12
# total number of items: 126
它看起来像你的'inv.update(龙)'是不正确的,除非你真的想扔掉你已经拥有的所有金币,当你拿起龙的藏匿。 – user2357112
您是否试图缩短完成相同任务所需的物理线数? –
哦哇user235我没有注意到! –