Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

One line for and if python

I try to understand the working of the python one-line method… So I decided to code this :

pizza_result=[[1, 1], [2, 3], [3, 0]]
b=0
pizza_result=[i for i in  pizza_result if i[1]>=b]

But Now I would like change the value of b…

As:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

izza_result=[i for i in  pizza_result if i[1]>=b: b=i[1] ]

But this doesn’t work…

Where I have to but the =i[1]?

In a nutshell :

What I expect

I would like the element(s) who have the biggest i[1]

In This code what’s aim the output ?

Here, I just want [[2,3]] because i[1] (3) > the other

BUT

But if I had : [[1,1],[2,1],[3,0]] I expect have : [[1,1],[2,1]]. Because the second number is >

>Solution :

You can use max to first get max value, and then use list comprehension to filter:

pizza_result=[[1, 1], [2, 3], [3, 0], [4, 3]]

max_val = max(p[1] for p in pizza_result)
output = [x for x in pizza_result if x[1] == max_val]
print(output) # [[2, 3], [4, 3]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading