切掉一个名字

2024-06-17 10:58:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个要切分的命名元组:

>>> from collections import namedtuple
>>> coords = namedtuple('coords', ['lng', 'lat', 'alt'])
>>> everest = coords(86.92, 27.97, 8848)

所以现在我可以很容易地访问属性了

^{pr2}$

但是,当我只想使用经度和纬度时(例如在某些几何算法中),我将对元组进行切片

>>> flag = everest[:2]
>>> flag.lat
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'lat'

我想知道是否可以对namedtuple进行切片,而只保留切片部分的属性。在


Tags: fromimport属性切片coordsaltnamedtuple命名
1条回答
网友
1楼 · 发布于 2024-06-17 10:58:19

您可以为此编写一个helper方法,将自定义的__getitem__附加到所创建的namedtuple类。__getitem__每次都会创建一个新类,但使用切片的参数数量较少

from collections import namedtuple


def namedtuple_with_slice(name, args):
    cls = namedtuple(name, args)
    def getitem(self, index):
        # `type(self)` can result in issues in case of multiple inheritance.
        # But shouldn't be an issue here.
        value = super(type(self), self).__getitem__(index)
        if isinstance(index, slice):
            cls = namedtuple(name, args[index])
            cls.__getitem__ = getitem
            value = cls(*value)
        return value
    cls.__getitem__ = getitem
    return cls

演示:

^{pr2}$

相关问题 更多 >