-1

So Here is my code for my lab coding project that I am currently working on:

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

My question to you as a beginner is: what method(s) should I use to allow my program to index specific parts of the list?

For example, how do I go about indexing a list of all of the restaurants from the greater list? This list includes just the restaurants from the list not all the other information like the phone numbers, etc...

I have used both slice methods and list functions in attempt to figure this out myself and it did not prove to work. >:(

Moshe
  • 9,283
  • 4
  • 29
  • 38

2 Answers2

1

I am not sure when you say index if you just want the values or for performance. But for basic retrieval you could just do something like this

[r.name for r in RC]

Which would give you all the names of restaurants you have in RC

You could get fancier,

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

Then you can just do,

getValues('name')

If you need it to cache you can look into using memoize

elb0w
  • 11
  • 1
0

Not completely sure what you mean by "index", but this might do what you want:

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

Output:

['Thai Dishes', 'Nobu', 'Nonna', 'Jitlada', 'Nola', 'Noma', 'Addis Ababa']
martineau
  • 119,623
  • 25
  • 170
  • 301