-1

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

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)]

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

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

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

4

2 回答 2

1

如果您只是想要值或性能,我不确定您何时说索引。但是对于基本检索,你可以做这样的事情

[r.name for r in RC]

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

你可以变得更花哨,

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

然后你可以这样做,

getValues('name')

如果需要缓存,可以考虑使用 memoize

于 2013-03-28T22:13:21.673 回答
0

不完全确定您所说的“索引”是什么意思,但这可能会满足您的要求:

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']
于 2013-03-28T22:46:22.040 回答