python - 从namedtuple中获取特定对象的对象名

标签 python python-2.7

我最近发现了 namedtuple 并想用它来替换我讨厌的大型类定义,但我很好奇是否有一种聪明的方法来检索我刚刚选择的值的对象名称,如果不清楚,请参阅下面的示例;

MyStruct = namedtuple("MyStruct","Var1 Var2 Var3")
Instance = MyStruct(1,2,3)
# What I currently do (but hopefully there is a smarter way to do this)
print "Var1:\t"+str(Instance.Var1)+"Var2:\t"+str(Instance.Var2) #and so forth

我知道有一个 _fields 选项,看起来像这样:

for x in Instance._fields:
  if str(x) == "Var1" or ... : # I only want to show certain objects at this time
    print x, getattr(Instance,x)

对我来说,它仍然看起来相当不Pythonic,那么有没有更好的方法来做到这一点?

最佳答案

namedtuple 实例有一个 namedtuple._asdict() method返回一个有序字典:

>>> from collections import namedtuple
>>> MyStruct = namedtuple("MyStruct", "Var1 Var2 Var3")
>>> value = MyStruct('foo', 'bar', 'baz')
>>> value._asdict()
OrderedDict([('Var1', 'foo'), ('Var2', 'bar'), ('Var3', 'baz')])

这将为您提供一个有序字典,其中的键和值与内容相对应。

但是,我不清楚您想要实现什么目标;直接选择正确的字段到底有什么问题?

print 'Var1: {}'.format(value.Var1)

或使用str.format()挑选特定字段:

print 'Var1: {0.Var1}, Var3: {0.Var3}'.format(value)

关于python - 从namedtuple中获取特定对象的对象名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19840457/

相关文章:

python - 如何在 Python 上的 Couchbase 中执行类似 "SELECT DISTINCT(HOSTNAME) from *"的查询

python - Lambda 函数导致 TypeError : 'int' object is not iterable

python - 将命令提示符输出重定向到 python 生成的窗口

python - boto3 python change_resource_record_sets

python - 从 pandas 中的多索引日期获取频率表

python - 在python中将标准错误输出重定向到/dev/null

python - Scrapy脚本运行无异常,但没有收集到数据

python-2.7 - NLTK - 如何使用 NER

python - 我一辈子都画不出来

Python 将变量中编辑后的 ​​NaN 写入 .csv