How to cast tuple into namedtuple?

前端 未结 1 1610
借酒劲吻你
借酒劲吻你 2021-02-05 00:26

I\'d like to use namedtuples internally, but I want to preserve compatibility with users that feed me ordinary tuples.

from collections import namedtuple

tuple_p         


        
相关标签:
1条回答
  • 2021-02-05 01:19

    You can use the *args call syntax:

    named_pi = Record(*tuple_pi)
    

    This passes in each element of the tuple_pi sequence as a separate argument.

    You can also use the namedtuple._make() class method to turn any sequence into an instance:

    named_pi = Record._make(tuple_pi)
    

    Demo:

    >>> from collections import namedtuple
    >>> Record = namedtuple("Record", ["ID", "Value", "Name"])
    >>> tuple_pi = (1, 3.14, "pi")
    >>> Record(*tuple_pi)
    Record(ID=1, Value=3.14, Name='pi')
    >>> Record._make(tuple_pi)
    Record(ID=1, Value=3.14, Name='pi')
    
    0 讨论(0)
提交回复
热议问题