Comparing lists with min () based on out of order comparison

I have a list of lists, for example q = [[1,2],[3,4]]

, where each sub-list is a list of 2 integers, and I return the index of each endpoint (I think?).

I need a list index with a min / max value in the second record from all second subscription records and where there are other sublists with the same value in the second record, the index with first returns the min / max value from the min / max list of the second value.

For example, if q = [[1, 2], [3, 4], [1, 0], [0, 5]]

, and I need a minute second, if an anchor then min second and then first. So I need min(S)

to return [1,0]

. Instead, it seems to be returning [0,5]

.

>>> q = [[1,2],[3,4]]
>>> min(q)
[1, 2]
>>> q.append([1,0])
>>> min(q)
[1, 0]
>>> q.append([0,5])
>>> min(q)
[0, 5]
>>> q
[[1, 2], [3, 4], [1, 0], [0, 5]]

      

As per this answer here , comparing lists compares them in order of elements using the following list entry for tiebreaks.

>>> q.append([0,6])
>>> q.append([0,4])
>>> min(q)
[0, 4]
>>> q
[[1, 2], [3, 4], [1, 0], [0, 5], [0, 6], [0, 4]]
>>> 

      

Is there any way to control the ordering in comparison? I've tried reading the documentation , but I don't understand what I am reading.

+3


source to share


3 answers


Does this work for you?



min(q, key = lambda x: (x[1],x[0]))

      

+1


source


Use the keyword argument key

in [ min()

] (1]:

Example:

>>> from operator import itemgetter
>>> q = [[1, 2], [3, 4], [1, 0], [0, 5]]
>>> min(q, key=itemgetter(1, 0))
[1, 0]

      



This sorts the iterative q

with a key function itemgetter(1, 0)

that basically returns tuple

of (2nd-item, 1st-item)

and is equivalent min(q, key=lambda x: (x[1], x[0]))

.

min(iterable[, key])

min(arg1, arg2, *args[, key])

\

Returns the smallest element in an iterable, or the smallest of two or more arguments.

If a single positional argument is provided, the iterable must be a non-empty iterable (for example, a non-empty string, tuple, or list). Smallest Returns the item in the iterable. If there are two or more positional arguments, the smallest of the positional arguments is returned.

The optional key argument specifies a single-argument ordering function as for list.sort (). The key argument, if supplied, must be in the form of a keyword (for example, min (a, b, c, key = func)).

Changed in version 2.5: Added support for an optional key argument.

+2


source


You can use extended snippet syntax to override helper lists:

>>> q = [[1, 2], [3, 4], [1, 0], [0, 5]]
>>> min(q, key=lambda sl: sl[::-1])
[1, 0]

      

+1


source







All Articles