【问题标题】:Mapping over namedtuple as dictionary将namedtuple映射为字典
【发布时间】:2017-04-06 21:10:56
【问题描述】:

有没有一种简单的方法来映射/理解命名元组,例如

[k + v for k,v in namedtuple]

我觉得我可以使用 asDict 为此编写一个简单的 map 函数,但是对于推导式呢?

【问题讨论】:

    标签: python collections


    【解决方案1】:

    如果要使用列表推导,我们必须更多地了解 namedtuple 数据是什么样子的。

    另外,更广泛的方法是使用递归函数来解包嵌套数据结构:

    def reducer(obj):
        if isinstance(obj, dict):
            return {key: reducer(value) for key, value in obj.items()}
        elif isinstance(obj, list):
            return [reducer(value) for value in obj]
        elif isnamedtupleinstance(obj):  # see note
            return {key: reducer(value) for key, value in obj._asdict().items()}
        elif isinstance(obj, tuple):
            return tuple(reducer(value) for value in obj)
        else:
            return obj
    

    注意:如果您的 namedtuple 包含其他 namedtuples,您将需要 check for instances of namedtuples 的这个辅助方法,这样它们就不会被误认为是实际的元组:

    def isnamedtupleinstance(x):
        _type = type(x)
        bases = _type.__bases__
        if len(bases) != 1 or bases[0] != tuple:
            return False
        fields = getattr(_type, '_fields', None)
        if not isinstance(fields, tuple):
            return False
        return all(type(i)==str for i in fields)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-10
      • 2018-11-17
      • 1970-01-01
      • 1970-01-01
      • 2015-10-17
      • 2013-04-26
      • 2014-09-12
      • 2010-12-31
      相关资源
      最近更新 更多