C.Ung
C.Ung

Reputation: 3

Trying to filter a list to bring back lines with a specific word

I just started learning python a week ago and am stuck on this exercise. I had to read in a csv file of employees and there salaries and return a list with lines splitted at the tab. The list looks like this:

employees = [['ID','Title','Salary','Base'],
             ['453334','Professor','0.56','.40'],
             ['4353434','Tutor','0.66','0065'.....]]

I have to filter the list to only keep those employees who are professors. I know that I need something that prints those items where the column 4 value == "Professor". Here's what I have so far:

employees2 = []
def professor(x):
    for line in x:
       if x[?][4] == "Professor":
          employee2.append(line)
    return employee2

I just have no idea how to get it to look at every row, and only column 4 to output a list only keep those with the title or professor.

Upvotes: 0

Views: 36

Answers (1)

matsjoyce
matsjoyce

Reputation: 5844

Maybe:

def professor(x):
    employees2 = []
    for line in x:
       if line[1] == "Professor":
          employees2.append(line)
    return employees2

The shorter (and more pythonic way) is:

employees2 = [line for line in employees if line[1] == "Professor"]

If you have to make a function:

def professor(x):
    return [line for line in x if line[1] == "Professor"]

Or (and someone will probably shout at me for this):

professor = lambda x: [line for line in x if line[1] == "Professor"]

Upvotes: 1

Related Questions