Spinnaay Spinnaay - 2 months ago 7
Python Question

Accessing object from list comprehensive search in Python

I am using a list comprehensive 'search' to match objects of my employee class. I then want to assign a value to them based on who matched the search.

Basically the code equivalent of asking who likes sandwiches and then giving that person a sandwich.

This bit works

class Employee():
def __init__(self, name, age, favoriteFood):
self.name = name
self.age = age
self.favoriteFood = favoriteFood

def __repr__(self):
return "Employee {0}".format(self.name)

employee1 = Employee('John', 28, 'Pizza')
employee2 = Employee('Kate', 27, 'Sandwiches')

myList = [employee1, employee2]

a = 'Sandwiches'
b = 'Tuna Mayo Sandwich'
matchingEmployee = [x for x in myList if x.favoriteFood == a]

print matchingEmployee


This prints 'Employee Kate' from the class repr

The bit I'm stuck on is now giving Kate the Tuna Mayo Sandwich, value b.

I was hoping to do something like

matchingEmployee.food = b


But this doesn't create a new variable in that object and give it the value b.

Any help would be greatly received.

Answer

If you want to append food to each employee that matched your filter you'd need to loop through the matchingEmployee list. For example:

for employee in matchingEmployee:
    employee.food = b
Comments