如何打印 **Kwargs 中的值

问题描述 投票:0回答:1

所以我正在制作一个基于文本的游戏,需要我有多个通向其他房间的门和多个物品。我可以使用 *args 运算符很好地列出门,但是当我使用 **kwargs 列出项目时,它会给我一本字典,当我打印值时,它会给我(例如)'dict_list['magazine ']'。如何摆脱“dict_list”并打印该值?

我尝试使用 .values(),如上所述

这是一个片段:

class Room:
    def __init__(self, desc, *doors, **items):
        self.desc=desc
        self.doors=doors
        self.items=items

    def describe_room(self):
        print(f"\ndescription = {self.desc}")
        print(f"\ndoors = {self.doors}")
        print(f"\nThe room contains: {self.items.values()}")
        for item in self.items.values():
            inventory.append(item)
        print(f"\nInventory: {inventory}")
Living_Room=Room('it stinks in here', 'door to bathroom', 'door to fireplace', item_1='gun', item_2='magazine')

但这没有用。我很困惑。我尝试使用 .join() 方法。我想加入这些值,而不是直接打印它们,看看这是否会起到任何作用,但事实并非如此。这是我尝试过的片段:

def describe_room(self):
    print(f"\ndescription = {self.desc}")
    print(f"\ndoors = {self.doors}")
    items_list = self.items.values()
    print(f"\nThe room contains: {self.join(items_list)}")
    for item in self.items.values():
        inventory.append(item)
    print(f"\nInventory: {inventory}")
Living_Room=Room('it stinks in here', 'door to bathroom', 'door to fireplace', item_1='gun', item_2='magazine')

请对我宽容一点,哈哈,我对编程很陌生。任何和所有的回答将不胜感激

python keyword-argument
1个回答
0
投票

当您将任何类型传递给

print()
时,Python 会尝试获取该类型以字符串形式提供其表示形式或值。

对于字符串来说,这很简单 - 要打印

'Hello world!'
,它只打印字符
Hello world
,尽管即使如此,还是有一些规则,就像您在代码中一样(您使用
\n
来指示换行符)。

对于复杂类型,例如字典或列表,事情就没那么简单了。通常,没有确切的“字符串值”,但有变量的表示形式,就像 Python 代码中出现的那样。例如:

xs = [1, 2, 3]
print(xs)  # prints "[1, 2, 3]" (without the quotes)
d = {1: "one", 2: "two"}
print(d)  # prints "{1: 'one', 2: 'two'}"

请注意,打印变量似乎只是获取 Python 代码中定义的内容 - 但事实并非如此。如果您仔细观察字典

d
的打印方式,您会注意到单引号被打印在字符串值周围,因为这是 Python 中的默认设置,即使它们是用双引号定义的(这是一种替代方法,也可以有效)。

通常,您希望更好地控制某些内容的打印方式,而不是仅仅依赖于标准类如何呈现自身。例如,您可能希望将列表打印为一系列由逗号和空格分隔的数字,不带方括号:

xs = [1, 2, 3]
print(', '.join(xs))

这会导致错误,因为

.join
只能将一堆字符串连接在一起,而
xs
包含整数,因此需要将整数显式转换为字符串(即使
print()
在刚刚执行时会自动执行此操作)打印单个整数):

xs = [1, 2, 3]
print(', '.join(map(str, xs)))

在您的情况下,您尝试加入的内容似乎是某些字典的值(没有键):

print(', '.join(self.items.values()))

但是,目前还不清楚为什么您希望将它们作为字典而不是列表传递。如果您提出您想要做的事情,将会更有帮助,因为您的问题很可能是 XY 问题 的一个例子,也就是说您所询问的解决方案并不是根本问题的最佳解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.