Function of key and lambda in functions "max ()" or "min ()", Python [closed]

0

I would like to understand what is the operation and the creation of "keys" or "lambdas" that can condition the max () or min () functions, applied to lists, dictionaries or tuples.

    
asked by Jesus_jbs 24.11.2018 в 10:08
source

1 answer

2

The functions max() and min() , as well as the function sorted() need to know how to compare two values, to determine in what order to put them and therefore what is the maximum or minimum.

By default Python already has ways to compare the basic types (integer, string, tuple, etc.). For your own types (classes) the class can incorporate a .__lt__() method that is evaluated to make the comparison < , and if it is the case that the class incorporates those methods, sorted() , max() and min() will use them for their sorting.

For the case in which you want to alter the default python rules (or those that incorporate the class in your .__lt__() method, you can provide a parameter called key to these functions.

That parameter is the name of another function that you must program separately, or of a lambda if the function is so simple that it consists merely of returning an expression. Either a function or a lambda its operation is the same:

  • Receive a parameter that is an element of the list you are sorting
  • Returns a value that can be integer, string, tuple, or one of the types that python already knows how to sort. That value represents the "sort value" of that element.

Python is calling your function key for each element of the list you want to sort, and sorts it according to the value returned by key . It is as if you had transformed all the elements of your list into others (those that return key ), ordered those others, and then substituted each one for its original value.

An example (list of tuples)

Imagine that your elements are tuples. By default python already knows how to order them and its method is to order according to the value of the first element of the tuple, and if they are equal by the second, etc. So:

mis_datos = [(1,20), (5,3), (3,1), (2, 10)]
print("Ordenada: ", sorted(mis_datos))
print("Maximo: ", max(mis_datos))
Ordenada:  [(1, 20), (2, 10), (3, 1), (5, 3)]
Maximo:  (5, 3)

But it turns out that we want to be ordered by the second element . We then need to make a function that will receive each tuple and return the second element, for example like this:

def get_segundo_elemento(tupla):
    return tupla[1]

Using this function as key :

print("Ordenada: ", sorted(mis_datos, key=get_segundo_elemento))
print("Maximo: ", max(mis_datos, key=get_segundo_elemento))
Ordenada:  [(3, 1), (5, 3), (2, 10), (1, 20)]
Maximo:  (1, 20)

In this case the function is very simple, in other cases it could contain conditional, loops or what you need to compute a "sort value". In cases as simple as these it may not be worth defining a function and inventing a name for it, especially if you are not going to use it anywhere else. You can use a lambda expression instead:

print("Ordenada: ", sorted(mis_datos, key=lambda x: x[1]))

What's more, for this particular case you do not even need to write the function, because it is a common case that python already provides functions for it in its operator module.

from operator import itemgetter
print("Ordenada: ", sorted(mis_datos, key=itemgetter(1)))

Here the syntax can be more confusing, because itemgetter(1) is a function that when executed, returns you another function , which waits as a parameter a list or tuple, and returns its index element 1. Personally I find the expression lambda clearer, but it is convenient to know the existence of the possibilities that operator gives you for functional programming.

Another example (list of dictionaries)

To compare dictionaries python does not have default method, so in this case it is essential to give a key . The most typical case is to want to sort the list by a particular field of the dictionary. The mechanism is similar to that seen for the tuple. For example:

mis_datos = [
    { "nombre": "Juan", "edad": 40},
    { "nombre": "Arturo", "edad": 49 },
    { "nombre": "Javier", "edad": 61 },
    { "nombre": "Rodrigo", "edad": 45 }]

sorted(mis_datos, key=lambda x: x["nombre"])
sorted(mis_datos, key=lambda x: x["edad"])

Or if you prefer:

sorted(mis_datos, key=itemgetter("nombre"))
sorted(mis_datos, key=itemgetter("edad"))

Note, however, that it is assumed that all the elements in the list are dictionaries that have the key in question.

If you have particular doubts about how to define a key function for your particular list, ask again by giving details of what the elements of the list are and what sort you would like for them.

    
answered by 24.11.2018 / 10:48
source
Join several arrays into one two-dimensional in PHP ___ ___ As erkimt make the main image occupies 100% of width and height ______ qstntxt ___

I would like to know how to do so that the main image of a page has a high of 100% of the browser mainly without the need to apply pixels.

I can do it by applying the pixels but when viewing it from another pc or a monitor with different screen resolutions this one does not look the same since it had it pre-defined for a specific resolution.

I want to achieve something like this See Here , that As you can see when the page is opened there is a main image and if you see it from another device you can still see the same without any distortion or the image is cut off. Eye, the page is not mine I just put it as an example.

My code:

%pre% %pre%
    
______ azszpr174982 ___

CSS has a set of properties that do exactly what you're looking for

%code% causes the image to be applied to the entire container without showing the leftovers on the sides or up and down

%code% causes the origin of the image to be the vertical and horizontal center

%pre% %pre%
    
______ azszpr174984 ___

if you apply this code to a div:

%pre%

I should give you the height and width of the page at that time, also if you put a background image to the div you can put:

%pre%     
___