Home > Enterprise >  Getting attributte value from object where other value in this object is the biggest
Getting attributte value from object where other value in this object is the biggest

Time:02-04

I have this list of objects which have p1, and p2 parameter (and some other stuff).

Job("J1", p1=8, p2=3)
Job("J2", p1=7, p2=11)
Job("J3", p1=5, p2=12)
Job("J4", p1=10, p2=5)
...
Job("J222",p1=22,p2=3)

With python, I can easily get max value of p2 by

(max(job.p2 for job in instance.jobs))

but how do I get the value of p1, where p2 is the biggest?

Seems simple, but I can't get it anyway... Could You guys help me?

CodePudding user response:

You could loop like this:

mx = -inf

for job in instance.jobs:
    if job.p2 > mx:
        mx = job.p2
        var = job
print(mx)
print(var)
print(var.p1)

Example output:

12
<object>
5

CodePudding user response:

If instance.jobs is the iterable you want to check and all elements have a p1 and a p2 attribute, use

max(instance.jobs, key=lambda job: job.p2).p1

If there are multiple jobs where p2 is largest, you will get an arbitrary p1 value from one of those jobs.

  •  Tags:  
  • Related