【问题标题】:How to convert a namedtuple into a list of values and preserving the order of properties?如何将命名元组转换为值列表并保留属性的顺序?
【发布时间】:2011-08-02 08:08:19
【问题描述】:
from collections import namedtuple
Gaga = namedtuple('Gaga', ['id', 'subject', 'recipient'])
g = Gaga(id=1, subject='hello', recipient='Janitor')

我希望能够获得这个列表(它保留了属性的顺序):

[1, 'hello', 'Janitor']

我可以自己手动创建此列表,但必须有更简单的方法。 我试过了:

g._asdict().values()

但是属性不是我想要的顺序。

【问题讨论】:

  • 一个命名元组已经是一个值序列(就像一个列表)。什么不工作? g[0]== 1 and g[1]=='subject and g[2]='recipient'。既然它的行为已经很像一个列表,你还需要什么?
  • @S.Lott 非常感谢,我为忘记它仍然是一个元组而感到很愚蠢,我把它当作字典-_-

标签: python


【解决方案1】:

为什么不只是list

>>> list(g)
[1, 'hello', 'Janitor']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 2012-04-08
    • 1970-01-01
    • 2014-09-19
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多