1

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?

Lenni
  • 15
  • 4
  • You should look at answers to this [question](https://stackoverflow.com/questions/18296755/python-max-function-using-key-and-lambda-expression). – quamrana Feb 03 '22 at 14:27
  • Did something like this, but I think it makes no sense and adds to much job (but it works...) ```for job in instance.jobs: maxp1=(max(job.p2 for job in schedule.instance.jobs)) if job.p2 == maxp1: print(job.p1)``` – Lenni Feb 03 '22 at 14:29

2 Answers2

0

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.

timgeb
  • 76,762
  • 20
  • 123
  • 145
  • This also works... Python is a great thing, thanks a lot! Gotta get used&learn how to use lambda functions – Lenni Feb 03 '22 at 14:50
0

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
Eli Harold
  • 2,280
  • 1
  • 3
  • 22
  • Oh, so this is that simple... damn Thanks a lot, it works, and I think i understand it :D – Lenni Feb 03 '22 at 14:48