Search for a tuple in the list of tuples (sort by multiple keys)

I try to find a tuple in the list of tuples, but don't get how to do it

I have the following list (id, price, count)

[('1', 3.0, 6), ('2', 2.0, 2), ('3', 2.0, 5), ('4', 4.0, 2), ('5', 2.0, 5), ('
6', 3.0, 6), ('7', 3.0, 5), ('8', 2.0, 5), ('9', 3.0, 5), ('10', 3.0, 5)]

condition for tuple search:

  • tuple should have a minimum price.
  • tuple must have a maximum counter value.
  • The priority of the first condition is higher than the second.

Please tell me how to achieve these conditions in order to find the tuple in the list.

+4
source share
3 answers

You can build a key for sorted from two elements of your list items: (price, -count)(minus the score is used to invert the direction - more value will be the first as a result):

t = [('1', 3.0, 6), ('2', 2.0, 2), ('3', 2.0, 5), ('4', 4.0, 2), ('5', 2.0, 5),
     ('6', 3.0, 6), ('7', 3.0, 5), ('8', 2.0, 5), ('9', 3.0, 5), ('10', 3.0, 5)]

>>> sorted(t, key=lambda i: (i[1], -i[2]))
[('3', 2.0, 5), ('5', 2.0, 5), ('8', 2.0, 5), ('2', 2.0, 2), ('1', 3.0, 6),
 ('6', 3.0, 6), ('7', 3.0, 5), ('9', 3.0, 5), ('10', 3.0, 5), ('4', 4.0, 2)]

, min , :

>>> min(t, key=lambda i: (i[1], -i[2]))
('3', 2.0, 5)
+1

min/max . , , ,

, ,

a > b -> -a < -b. , , . , max/min, ,

>>> min(t, key = lambda e: (e[1], -e[2]))
('3', 2.0, 5)
>>> max(t, key = lambda e: (-e[1], e[2]))
('3', 2.0, 5)
+2

, Python docs.

x = [('1', 3.0, 6), ('2', 2.0, 2), ('3', 2.0, 5), ('4', 4.0, 2), ('5', 2.0, 5),
     ('6', 3.0, 6), ('7', 3.0, 5), ('8', 2.0, 5), ('9', 3.0, 5), ('10', 3.0, 5)]

count :

x1 = sorted(x, key=lambda t: t[2], reverse=True) 

"":

x2 = sorted(x1, key=lambda t: t[1])

Now the optimal tuple is the first element x2. Find all the values ​​corresponding to the optimal value in x2:

optimal = (x2[0][1], x2[0][2])
[v for v in x2 if v[1]==optimal[0] and v[2]==optimal[1]]
# -> [('3', 2.0, 5), ('5', 2.0, 5), ('8', 2.0, 5)]
0
source

Source: https://habr.com/ru/post/1524466/


All Articles