简体   繁体   中英

Find maximum value of minimum elements in tuple

If I have a list

[[209, 34], [50, 170], [197, 32], [75, 156], [176, 51], [54, 141], [205, 19], [35, 173]]

How would I go about finding the sublist with the maximum minimum element?

ie, in the case above, it would be index [3] - [75,156] because it's minimum value is greater than the minimum value of all other elements.

It should be as simple as:

max(list_of_iterables, key=min)

ie:

>>> lst = [[209, 34], [50, 170], [197, 32], [75, 156], [176, 51], [54, 141], [205, 19], [35, 173]]
[[209, 34], [50, 170], [197, 32], [75, 156], [176, 51], [54, 141], [205, 19], [35, 173]]
>>> max(lst, key=min)
[75, 156]

The max (and min ) functions work by walking through an iterable and comparing each element in the iterable picking out the biggest (or smallest for min ) element. The catch is that the thing compared is the result of the key function applied to the individual element. By default, the key function is just the identity function -- but it can be anything you want. In this case, my key function is min which picks out the minimum value of the sub-list. We then compare the sublists based on their minimum value and pick out the max which is exactly what your question asked for.

You can use sorted function.

>>> lst = [[209, 34], [50, 170], [197, 32], [75, 156], [176, 51], [54, 141], [205, 19], [35, 173]]
[[209, 34], [50, 170], [197, 32], [75, 156], [176, 51], [54, 141], [205, 19], [35, 173]]
>>> sorted(lst, key=min, reverse=True)
[[75, 156],
 [54, 141],
 [176, 51],
 [50, 170],
 [35, 173],
 [209, 34],
 [197, 32],
 [205, 19]]

key=min means it will use min function when sorting the list.

Then you can find the index of the value with index method. Like:

>>> lst.index([75, 156])
3

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