-5

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:

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 >

2 Answers2

1

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]]
j1-lee
  • 13,764
  • 3
  • 14
  • 26
0

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

Use:

m = max(pizza_result, key=lambda x: x[1])[1]
[l for l in pizza_result if l[1] == m]

Output: [[2, 3], [4, 3]]

mozway
  • 194,879
  • 13
  • 39
  • 75
  • Ok, now it works, though I think it's pretty much the same as the other answer, just not as good. NB. I don't see the point of explaining a downvote when you can easily explain it yourself by testing. – Kelly Bundy Nov 14 '21 at 23:31
  • Add I said, this was a typo during copying the answer ;) – mozway Nov 14 '21 at 23:38