2013-03-28 103 views
-1

所以這是我對我的實驗室編碼項目代碼,我目前的工作: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)] 

我想問你作爲一個初學者是:什麼方法(S)我應該使用允許我的程序索引列表的特定部分?

例如,我怎麼去索引所有的大名單中餐館的名單?這份名單包括剛剛從列表中餐館不是所有的其他信息,如電話號碼,等...

我都用了分片方式和列表功能在試圖弄清楚這一點,我自己並沒有證明工作。 > :(

+0

我想我不知道你在這種情況下指數是什麼意思? – Colleen

+0

這是特定的疑問,實驗室提出,如果這有助於: –

+0

假設你的意思是'通過「所有餐館」 name','RC [0] .name'將是第一項。 – Moshe

回答

1

我不知道,當你說指數如果你只想值或性能,但對於基本檢索你可能只是做這樣的事情

[r.name for r in RC] 

這將使你所有的名字餐廳你在RC

你可以更大膽,

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

然後,你可以這樣做,

getValues('name') 

如果你需要緩存你可以考慮使用memoize的

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