1

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.

  • 2
    Note: though they are very similar, tuples and lists are distinct types. It's best not to use one term when you mean the other. – user2357112 Jun 01 '14 at 02:15
  • And a great reference for when to use one or the other is http://stackoverflow.com/questions/626759/whats-the-difference-between-list-and-tuples-in-python – mgilson Jun 01 '14 at 02:19

2 Answers2

6

It should be as simple as:

max(list_of_iterables, key=min)

i.e.:

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

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • as the op is probably new to python, some explanation would be helpful, I think – bcr Jun 01 '14 at 02:15
  • @bcr -- Yeah, that's probably true. I've added some explanation. – mgilson Jun 01 '14 at 02:19
  • will this only compare the first value, or both values in each sub list item? – Luke_Smith_Lukasaurus Jun 01 '14 at 02:35
  • @Luke_Smith_Lukasaurus -- It will compare the minumum value of each sublist and then return the sublist whose minimum value is the biggest. In the case of ties, the first sublist with that minimum value is returned. – mgilson Jun 01 '14 at 02:39
0

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
Kei Minagawa
  • 4,395
  • 3
  • 25
  • 43