从 namedtuple 中获取特定对象的对象名称 [英] Get the object name of a specific object from namedtuple

查看:53
本文介绍了从 namedtuple 中获取特定对象的对象名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

MyStruct = namedtuple("MyStruct","Var1 Var2 Var3")实例 = MyStruct(1,2,3)# 我目前在做什么(但希望有更聪明的方法来做到这一点)打印 "Var1:\t"+str(Instance.Var1)+"Var2:\t"+str(Instance.Var2) #等等

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

for x in Instance._fields:if str(x) == "Var1" or ... : # 我此时只想显示某些对象打印 x, getattr(Instance,x)

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

解决方案

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

<预><代码>>>>从集合导入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)

I have recently discovered namedtuple and want to use it to replace my icky large class definitions but I am curious if there is a smart way to retrieve the object's name of the value that I just selected, see the below example if it's unclear;

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

I know that there is the _fields option that would look something like this:

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)

Still it looks rather un-pythonic to me, so is there a better way to do this?

解决方案

A namedtuple instance has a namedtuple._asdict() method that returns an ordered dictionary:

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

This gives you an ordered dictionary with keys and values corresponding to the contents.

However, it is not clear to me what you are trying to achieve; what exactly is wrong with just selecting the right field directly?

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

or picking out specific fields with str.format():

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

这篇关于从 namedtuple 中获取特定对象的对象名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆