简体   繁体   中英

Finding tuple in the list of tuples (sorting by multiple keys)

I am trying to find tuple in the list of tuple, but not getting how to do that

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 finding tuple is:

  1. tuple should have minimum price .
  2. tuple should have maximum count value .
  3. priority of first condition is higher then second condition.

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

You can leverage the min / max builtin function to search your tile. Either of them would work, its only that you need to change the key function to use one over the other

For numerical values, negating a value changes its order

a > b -> -a < -b . Using this knowledge you can build a key as a tuple of two elements, the order depends on the order of priority. Based on whether you use max/min, you need to negate the appropriate variables,

>>> 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)

You can build key for sorted from two elements of your list items: (price, -count) ( minus count used to invert direction - bigger value will be first in 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)]

To find only one element you can use min function with same tuple as key argument:

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

You can sort on multiple keys by the method mentioned in 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)]

Sort by second priority key count first:

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

Then sort the result by the first key 'price`:

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

Now the optimal tuple is the first element of x2 . Find all values matching 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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM