2017-04-13 93 views
-1

我试图缩短我的代码的Python 3代码缩短

代码:

inv = {'arrow': 12, 'gold coin': 42, 'rope': 2, 'torch': 4, 'dagger': 1} 

def show_inv(): 
    print('inventory:') 
    item_total = 0 
    for k, v in inv.items(): 

     print(str(v)+ ' ' + (k)) 
     item_total = item_total + v 

    print('total number of items: ' + str(item_total)) 


show_inv() 


dragon = {'gold coin': 50, 'ruby': 15} 

inv.update(dragon) 

print() 
print('after slaying dragon:') 
show_inv() 

也没有用,所以我在这里:)

这是

结果:

库存:

12箭头

42金币

2绳

4炬

1匕首

总项数:61

杀龙后:

库存:

12箭头

50金币

2绳

4炬

1匕首 15红宝石 总项目数:84

+1

它看起来像你的'inv.update(龙)'是不正确的,除非你真的想扔掉你已经拥有的所有金币,当你拿起龙的藏匿。 – user2357112

+2

您是否试图缩短完成相同任务所需的物理线数? –

+0

哦哇user235我没有注意到! –

回答

2

可以使用sum功能,而不是总的逐渐增加,但除此之外,有没有一个整体很多事情可以做:

inv = {'arrow': 12, 'gold coin': 42, 'rope': 2, 'torch': 4, 'dagger': 1} 

def show_inv(): 
    print('inventory:') 
    for k, v in inv.items(): 
     print("%s %s" % (v,k)) 
    print('total number of items: %s' % sum(inv.values())) 

show_inv() 

dragon = {'gold coin': 50, 'ruby': 15} 

inv.update(dragon) 

print() 
print('after slaying dragon:') 
show_inv() 
+4

'print(“%s%s”%(v,k))'*与* print(v,k)'完全相同。同样,'print('项目总数:%s'%sum(inv.values()))'相当于'print('总项数:',sum(inv.values()))' – vaultah

+0

注意,虽然这使得代码“更短”,但与“更长”代码中所做的相比,它实际上会带来额外的优惠。 –

-1

至于更新库存,你可以尝试一个衬垫

取自
from functools import reduce 
inv = reduce(lambda x, y: dict((k, v + y[k]) for k, v in x.items()), (inv,dragon)) 

代码,我建议检查对方的回答也: How to sum dict elements

+0

这不是很清楚。 'iteritems'也可以是'items'。 –

+0

什么?这比'inv.update(龙)'更好吗?我甚至不知道这是在做什么,反而给我一个错误......我错过了什么? –

+0

当然,但这里的清晰度被认为是简短的,至于'items',你对Python 3.x是正确的。 @ juanpa.arrivillaga我试图总结一些像'金币'这样的东西,它在示例中被更新而不是总结。 – mucka

3

如果你真的想在最短的possib乐功能,您可以使用此一班轮;)

show_inv = lambda: print('inventory:\n%s\n%s' % ('\n'.join(['%s %s' % (k,v) for k,v in inv.items()]),'total number of items: %s' % sum(inv.values()))) 

(请不要这样做)

+2

实际上,在inv.items())中,print('inventory')或print('Total number of items:',sum(print(v,k)或v for k,v) '更短。 – vaultah

+0

@vaultah我得到一个语法错误,虽然我高度赞同codegolfing答案:) – TemporalWolf

+1

@TemporalWolf你在Python 2? Python 2的'print'是一个语句,所以不能用于表达式 – vaultah

3

之前“缩短”你的代码,以确保它是正确的。目前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 
+0

谢谢,编程了一段时间,并没有现在'Counter',总是使用一个肮脏的黑客使用字典 – mucka