Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3代码缩短_Python_Python 3.x - Fatal编程技术网

Python3代码缩短

Python3代码缩短,python,python-3.x,Python,Python 3.x,我试图缩短我的代码 代码: 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

我试图缩短我的代码

代码:

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()
没有用,所以我在这里:)

这是

结果:

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


您可以使用
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()

至于更新库存,你可以试试一个班轮

from functools import reduce
inv = reduce(lambda x, y: dict((k, v + y[k]) for k, v in x.items()), (inv,dragon))
代码取自,我建议检查其他答案:

如果您真的想要尽可能短的函数,您可以使用此单行程序;)

(请不要这样做)

在“缩短”代码之前,请确保它是正确的。当前将只覆盖条目

我建议使用而不是
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\u inv
。然而,此函数的唯一目的是打印对象的表示,您无法在其中“缩短”太多内容。这似乎是正确的

但是如果你有一个“对象”(<代码> DICT<代码>)和一个对象的函数,你应该考虑使用一个“类”来包装它。有一些方法允许您自定义“字符串”表示:因此可以使用这些方法代替显式函数(或方法)调用:


看起来你的
inv.update(dragon)
不正确,除非你真的想在捡起龙的藏品时扔掉你已经拥有的所有金币。你是否试图缩短完成同样任务所需的实际行数?哦,哇,我没有注意到!您应该使用
collections.Counter
对象,当您
update
时,该对象将求和<代码>打印(“%s%s”%(v,k))与
打印(v,k)
完全相同。类似地,
print(
print(
)等同于
print(
print(
注意,虽然这使代码“更短”,但与您在“更长”代码中所做的工作相比,它实际上需要额外的过程。这还不是很清楚。另外,
iteritems
也可以是
项。什么?这比
inv.update(dragon)
好多少???我甚至不知道这是想做什么,它给了我一个错误无论如何。。。我遗漏了什么吗?当然,但在这里,清晰是用简短来交换的,至于
你对Python3.x是正确的@juanpa.arrivillaga我试图总结相同的项目,如
金币
,这是在示例中更新的,而不是总结。什么的简短。据我所知,这是充满错误的。您正在将
dragon
传递给
reduce
,它将迭代其键,因此
lambda
中的
x
将是一个字符串,并为
x.iteritems
抛出一个错误。另外,
inv
是不可调用的,所以我不确定你对
inv((k,v+y[k])的期望是什么,在x.iteritems()中的k,v
会做什么,甚至想象
x.iteritems()
没有抛出错误……你发布的链接是关于总结口述列表中的项目,而不是字典。这不起作用,你自己试试看。实际上,
print('inventory')或print('Total number of items:'),sum(print(v,k)或v代表k,v在inv.items()中)
更短。@vaultah我在这一行中遇到语法错误,尽管我非常赞成codegolfing的答案:)@TemporalWolf你在Python 2上吗?Python2的
print
是一条语句,因此不能用于expressions@vaultah你说得对。我打开repl.it来做Py3,显然仍然点击Py2。谢谢,编程了一段时间,现在没有关于
计数器
,总是使用dicts进行肮脏的攻击
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