Spinnaay
Spinnaay

Reputation: 129

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.

Upvotes: 0

Views: 58

Answers (4)

Andrei Todo
Andrei Todo

Reputation: 39

Since the variable matchingEmployee is a list, and in the given context, Kate is the first in the list, you can do :

matchingEmployee[0].food = b 

Upvotes: 0

Bruce Peterson
Bruce Peterson

Reputation: 41

Use the command line python to write a simplified expression:

[ y for y in [1,2,3,4] if y %2 ==0]

You will see that it results in a list output

[2, 4]

Your "matchingEmployee" is actually a list of matching employees. So to "give a sandwich" to the first employee found (assuming there is one):

matchingEmployee[0].food = b

To "give a sandwich" to the list of employees:

for employee in matchingEmployee:
    employee.food = b

Upvotes: 0

Spinnaay
Spinnaay

Reputation: 129

As I've learnt that the list comprehensive produces a list (stupid as that might sound :) ) I've added a for loop to iterate over the matchingEmployee list to give the sandwich to whoever wants it.

if matchingEmployee:
print 'Employee(s) found'

for o in matchingEmployee:
    o.food = b

Thanks

Upvotes: 2

Hevlastka
Hevlastka

Reputation: 1948

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

Upvotes: 0

Related Questions