Python Namedtuple索引实例

2024-06-08 08:27:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为我的项目编写代码:

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

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

例如,我该如何索引大列表中所有餐厅的列表?这个列表只包括列表中的餐厅,而不是所有其他信息,如电话号码等。。。在

我使用了slice方法和list函数来尝试自己解决这个问题,但是没有成功。>;:(


Tags: of项目方法代码namefrom列表phone
2条回答

我不确定当你说索引时,你只是想要值还是为了性能。但是对于基本的检索,你可以这样做

[r.name for r in RC]

这会告诉你你在RC所有的餐馆的名字

你可以变得更花哨

^{pr2}$

那你就可以做了

getValues('name')

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

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

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

输出:

^{pr2}$

相关问题 更多 >