Home > database >  When creating a list of a class variables, how do I create a list of all values for a single attribu
When creating a list of a class variables, how do I create a list of all values for a single attribu

Time:02-16

I have a class with many attributes. I have created a list of these class variables. I'm trying to access each list entry's attribute2. Consider the example below.

class District:

    def __init__(self, num, a, p):
        self.num = num  
        self.Area = a  
        self.Perimeter = p

dist_list = [None] * 5
for i in range(5):
    dist_list[i] = District(i, Area[i], Perimeter[i])

Is there a simple command in Python that will let me access all Perimeters from dist_list? Perhaps something like dist_list(Population) or something?

CodePudding user response:

You have a list of instances. You can use a list comprehension to collect the Perimeter attribute of each instance:

perimeters = [x.Perimeter for x in dist_list]

(You could have defined dist_list itself with a list comprehension as well

dist_list = [District(i, Area[i], Perimeter[i]) for i in range(5)]

)

CodePudding user response:

@Chepner's answer is good I just figure I'd also mention

perimeters = map(lambda x : getattr(x,"Perimeter"),dist_list)

Perimeters will be a map object which you can cast to a list.

perimeters = list(perimeters)

  • Related