命名元组与字典 [英] Namedtuple vs Dictionary

查看:115
本文介绍了命名元组与字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在编写游戏,我需要一种数据类型,该数据类型可以存储范围从liststuplesstringsintegers的多个变量.我在使用dictionariesnamedtuples之间陷入了困境.

So I'm programming a game and I need a datatype that can store a multitude of variables ranging from lists, tuples, strings and integers. I'm torn between using either dictionaries or namedtuples.

GameData = namedtuple('GameData', ['Stats', 'Inventory', 'Name', 'Health'])
current_game = GameData((20,10,55,3), ['Sword', 'Apple', 'Potion'], 'Arthur', 100)

GameData = {'Stats': (20,10,55,3), 'Inventory': ['Sword', 'Apple', 'Potion'], 'Name': 'Arthur', 'Health': 100}

您看到的,这里最大的问题是所有这些值都可能更改,因此我需要一个可变的数据类型,而不是namedtuple.在文档中查看,namedtuples似乎具有._replace(),那么这使其可变吗?

You see, the biggest problem here is all of these values may change, so I need a mutable datatype, which is not the namedtuple. Looking in the docs, namedtuples appear to have ._replace(), so does that make it mutable?

我也喜欢namedtuples如何具有以name=value格式打印的__repr__方法.同样,为namedtuple中的每个值分配单独的__doc__字段的功能也非常有用. dictionaries有此功能吗?

I also like how namedtuples have a __repr__ method that prints in the name=value format. Also, the functionality of assigning separate __doc__ fields to each value in the namedtuple is very useful. Is there this functionality with dictionaries?

推荐答案

只需使用class. 字典的问题在于您不知道期望使用哪些键,而您的IDE将无法为您自动完成. namedtuple的问题在于它是不可变的. 使用自定义类,您可以同时获得可读属性,可变对象和很大的灵活性.一些可供考虑的替代方法:

Just use a class. The problem with dictionaries is that you don't know which keys to expect and your IDE won't be able to autocomplete for you. The problem with namedtuple is that is not mutable. With a custom class you get both readable attributes, mutable objects and a lot of flexibility. Some alternatives to consider:

  • 从Python 3.7开始,您可以使用dataclasses模块:

from dataclasses import dataclass

@dataclass
class GameData:
    stats: tuple
    inventory: list
    name: str
    health: int

  • 如果使用其他Python版本,则可以尝试 attrs 软件包:

  • In case other Python versions, you could try attrs package:

    import attr
    
    @attr.s
    class GameData:
        stats = attr.ib()
        inventory = attr.ib()
        name = attr.ib()
        health = attr.ib()
    

  • 这篇关于命名元组与字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆