How to access the attributes of all instances stored in a list?

281 Views Asked by At

Intro

Comming from this question

Python- creating object instances in a loop with independent handling

I was asking myself how to access the attributes of all rather than just a single instance, if you have created a list of instances.

Minimal Example

Consider creating a list of company instances with the attributes name and value. Now I would like to know, which of these companies does have the highest value.

So far I am simply storing the values of the value attribute in an array and then find the index of the maximum value.

import numpy as np

class Company(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

companies = []
for name in 'ABC':
    companies.append(Company(name, np.random.rand()))

l = len(companies)
liste = np.zeros(l)
for i in range(l):
    liste[i] = companies[i].value

ind = np.unravel_index(np.argmax(liste), liste.shape)
print("Highest value: ", liste[ind])
print("Company of highest value: ", companies[ind[0]].name)

Questions

1) Is there a different way to create this list of all attribute values without a for-loop?

2) Is there a direct way to find the instance in a list, for which the value of a certain attribute is maximal?

2

There are 2 best solutions below

0
Torbik On BEST ANSWER

It doesn't avoid for completely but replaces it with list comprehension:

from operator import attrgetter

max_val_company = max((c for c in companies), key=attrgetter('value'))

max_val_company will contain Company object having max value attribule.

2
Sach On

Instead of storing all the object in a global list and iterating over them, you can compare/store the value in global variable while initializing the object.

import numpy as np
maxval = []
maxname = []

class Company(object):
  def __init__(self,name,value):
    self.name=name
    self.value=value
    if len(maxval)>0 and maxval[0] < value :
      maxval[0]=value
    elif len(maxval)==0:
      maxval.append(value)