Python Namedtuple索引实例

时间:2013-03-28 22:02:04

标签: python namedtuple

所以这是我目前正在进行的实验室编码项目的代码:

from collections import namedtuple
Restaurant = namedtuple('Restaurant', 'name cuisine phone dish price')

# Restaurant attributes: name, kind of food served, phone number, best dish, price of that dish

RC = [Restaurant("Thai Dishes", "Thai", "334-4433", "Mee Krob", 12.50), 
      Restaurant("Nobu", "Japanese", "335-4433", "Natto Temaki", 5.50), 
      Restaurant("Nonna", "Italian", "355-4433", "Stracotto", 25.50), 
      Restaurant("Jitlada", "Thai", "324-4433", "Paht Woon Sen", 15.50), 
      Restaurant("Nola", "New Orleans", "336-4433", "Jambalaya", 5.50), 
      Restaurant("Noma", "Modern Danish", "337-4433", "Birch Sap", 35.50), 
      Restaurant("Addis Ababa", "Ethiopian", "337-4453", "Yesiga Tibs", 10.50)]

我作为初学者的问题是:我应该使用哪种方法来允许我的程序索引列表的特定部分?

例如,如何从更大的列表中索引所有餐馆的列表?此列表仅包括列表中的餐馆,而不包括电话号码等所有其他信息......

我已经使用了切片方法和列表函数来尝试自己解决这个问题并且它没有被证明有效。 >:(

2 个答案:

答案 0 :(得分:1)

如果你只想要价值或表现,我不确定你说索引的时间。但对于基本检索,你可以做这样的事情

[r.name for r in RC]

这将为您提供RC中所有餐馆的名称

你可能会变得更加漂亮,

RC = [...]
def getValues(name):
   return [getattr(r, name) for r in RC]

然后就可以了,

getValues('name')

如果您需要缓存,可以查看使用memoize

答案 1 :(得分:0)

不完全确定“index”是什么意思,但这可能会做你想要的:

from collections import namedtuple
Restaurant = namedtuple('Restaurant', 'name cuisine phone dish price')

# Restaurant attributes: name, kind of food served, phone number, best dish, price of that dish

RC = [Restaurant("Thai Dishes", "Thai", "334-4433", "Mee Krob", 12.50),
      Restaurant("Nobu", "Japanese", "335-4433", "Natto Temaki", 5.50),
      Restaurant("Nonna", "Italian", "355-4433", "Stracotto", 25.50),
      Restaurant("Jitlada", "Thai", "324-4433", "Paht Woon Sen", 15.50),
      Restaurant("Nola", "New Orleans", "336-4433", "Jambalaya", 5.50),
      Restaurant("Noma", "Modern Danish", "337-4433", "Birch Sap", 35.50),
      Restaurant("Addis Ababa", "Ethiopian", "337-4453", "Yesiga Tibs", 10.50)]

def retrieve(records, column):
    """ return list of values for column from a list of namedtuples """
    if records and column not in records[0]._fields:
        raise ValueError('invalid column name:' + repr(column))
    return [getattr(rec, column) for rec in records]

print retrieve(RC, 'name')

输出:

['Thai Dishes', 'Nobu', 'Nonna', 'Jitlada', 'Nola', 'Noma', 'Addis Ababa']