Avery9115
Avery9115

Reputation: 135

List Comprehension with Instances

I am trying out list comprehension and I am stuck with the below problem.

class Programmer():
    def __init__(self, name, years_at_umich=1, programs_written=0):
        self.name = name
        self.seniority = years_at_umich
        self.bonus_points = random.randrange(1000)
        self.programs_written = programs_written

    def shout(self, phrase_to_shout):
        print phrase_to_shout  # print is for ppl!

    def __str__(self):
        return "My name is {}, and I've been at UMich for about {} years.".format(self.name,self.seniority)

    def year_at_umich(self):
        return self.seniority

prog_tups = zip(names, seniority,programs_written)
print prog_tups

prints output

[('Albert', 1, 10), ('Bisi', 5, 500), ('Cai', 2, 20), ('Dinesh', 4, 131), ('Euijin', 1, 46)]

I am trying to use list Comprehension to create a list of Programmer instances out of the prog_tups list from above and save that list in the variable programmers.

My current code is below, I am not getting a traceback, but nothing happens:

programmers = [item for item in prog_tups]

Upvotes: 2

Views: 1758

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92894

In case if you don't have a custom Programmer class yet consider using collections.namedtuple subclass:

import collections

Programmer = collections.namedtuple('Programmer', 'name seniority programs_written')
prog_tups = [('Albert', 1, 10), ('Bisi', 5, 500), ('Cai', 2, 20), ('Dinesh', 4, 131), ('Euijin', 1, 46)]
programmers = [Programmer(n, s, p) for n,s,p in prog_tups]

# the first programmer
print programmers[0]

The output:

Programmer(name='Albert', seniority=1, programs_written=10)

To deal with your existing custom class, use the following approach:

prog_tups = [('Albert', 1, 10), ('Bisi', 5, 500), ('Cai', 2, 20), ('Dinesh', 4, 131), ('Euijin', 1, 46)]
programmers = [Programmer(*t) for t in prog_tups]

# the first programmer
print programmers[0]

The output:

My name is Albert, and I've been at UMich for about 1 years.

Upvotes: 2

Neil A.
Neil A.

Reputation: 841

If I understand your question correctly, you want to have a list of only the names. Seeing as the names are the first element in the tuples, a simple solution would be programmers = [item[0] for item in prog_tuples] to obtain only the names. To see if this works, simply print() it.

Upvotes: 0

Related Questions