0

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?

Ben
  • 13
  • 4

2 Answers2

0

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)
Sach
  • 904
  • 8
  • 20
  • Thanks so far. That way I gonna figure out the max value, but how to get the companies name?! – Ben May 31 '18 at 15:33
  • you can store the company name in the same way, either having a different variable keep the company name for highest value or store both in dict as key value pair. – Sach Jun 03 '18 at 05:24
0

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.

Torbik
  • 489
  • 3
  • 10