Programing

정렬 뒤의 구문 (key = lambda :…)

lottogame 2020. 6. 26. 08:11
반응형

정렬 뒤의 구문 (key = lambda :…)


sorted()인수 뒤에 숨겨진 구문을 이해하지 못합니다 .

key=lambda variable: variable[0]

되지는 lambda임의? variable다음과 같은 모양으로 두 번 언급 dict되었습니까?


key컬렉션의 항목을 비교하기 전에 변환하기 위해 호출되는 함수입니다. 전달 된 매개 변수 key는 호출 가능한 것이어야합니다.

를 사용 lambda하면 익명 함수 (호출 가능)가 작성됩니다. sorted호출 가능 의 경우 하나의 매개 변수 만 사용합니다. 파이썬 lambda은 매우 간단합니다. 실제로 한 가지만 수행하고 반환 할 수 있습니다.

의 구문은 lambda단어 lambda뒤에 매개 변수 이름 목록과 단일 코드 블록이옵니다. 매개 변수 목록과 코드 블록은 콜론으로 표시됩니다. 이뿐만 아니라 같은 파이썬에서 다른 구조와 유사하다 while, for, if등등. 이들은 일반적으로 코드 블록이있는 모든 문장입니다. Lambda는 코드 블록이있는 명령문의 또 다른 인스턴스입니다.

람다의 사용과 def의 사용을 비교하여 함수를 만들 수 있습니다.

adder_lambda = lambda parameter1,parameter2: parameter1+parameter2
def adder_regular(parameter1, parameter2): return parameter1+parameter2

람다는 이름을 지정하지 않고 이것을 수행하는 방법을 제공합니다. 함수의 매개 변수로 사용하기에 좋습니다.

variable 콜론의 왼쪽에는 매개 변수의 이름이 있고 오른쪽에는 코드 블록에서 무언가를 계산하기 때문에 여기에서 두 번 사용됩니다.


나는 여기에있는 모든 대답이 sorted ()의 맥락에서 람다 함수가하는 일의 핵심을 다루고 있다고 생각하지만, 여전히 직관적 인 이해로 이어지는 설명처럼 느껴지므로 여기에 2 센트가 있습니다.

완전성을 기하기 위해, 나는 명백한 선행을 언급 할 것이다 : sorted ()는 정렬 된 요소들의 목록을 반환하고 우리가 특정한 방식으로 정렬하고 싶거나 복잡한 요소들의 목록 (예를 들어 중첩 된 목록 또는 튜플 목록) 키 인수를 호출 할 수 있습니다.

저에게는 주요 논점에 대한 직관적 인 이해, 그것이 왜 호출 가능해야하는지, 그리고 이것을 달성하기위한 (익명 적) 호출 가능 함수로 람다를 사용하는 것이 두 부분으로 나옵니다.

  1. 람 바를 사용한다는 것은 예를 들어 제공된 부기 와 같이 전체 함수를 작성 (정의) 할 필요가 없음을 의미합니다 . Lambda 함수는 생성, 사용 및 즉시 소멸되므로 한 번만 사용되는 더 많은 코드로 코드를 확장하지 않습니다. 이것은 내가 이해하는 것처럼 람다 함수의 핵심 유틸리티이며 이러한 역할에 대한 응용 프로그램은 광범위합니다. 그것의 문법은 순전히 관례에 의한 것이며, 본질적으로 일반적으로 프로그래밍 문법의 본질입니다. 구문을 배우고 완료하십시오.

람다 구문은 다음과 같습니다.

람다 input_variable (s) : 맛있는 하나의 라이너

예 :

In [1]: f00 = lambda x: x/2

In [2]: f00(10)
Out[2]: 5.0

In [3]: (lambda x: x/2)(10)
Out[3]: 5.0

In [4]: (lambda x, y: x / y)(10, 2)
Out[4]: 5.0

In [5]: (lambda: 'amazing lambda')() # func with no args!
Out[5]: 'amazing lambda'
  1. key인수 뒤에 숨겨진 아이디어 는 기본적으로 정렬하는 데 사용해야하는 목록 요소에서 'sorted ()'함수를 가리키는 일련의 명령어를 사용해야한다는 것입니다. 그것이 말할 때 key=, 실제로 의미하는 것은 : 한 번에 하나의 요소 (예 : e의 목록)를 목록을 반복 할 때 현재 요소를 핵심 인수에서 제공하는 함수에 전달하고 사용합니다. 최종 정렬 목록의 순서를 알려주는 변환 된 목록을 작성합니다.

확인 해봐:

mylist = [3,6,3,2,4,8,23]
sorted(mylist, key=WhatToSortBy)

기본 예 :

sorted(mylist)

[2, 3, 3, 4, 6, 8, 23] # 모든 숫자는 작은 순서에서 큰 순서로 표시됩니다.

예 1 :

mylist = [3,6,3,2,4,8,23]
sorted(mylist, key=lambda x: x%2==0)

[3, 3, 23, 6, 2, 4, 8] #이 정렬 된 결과가 직관적입니까?

내 람다 함수가 정렬하기 전에 (e)가 짝수인지 홀수인지 확인하라는 정렬을 지시했습니다.

BUT WAIT! You may (or perhaps should) be wondering two things - first, why are my odds coming before my evens (since my key value seems to be telling my sorted function to prioritize evens by using the mod operator in x%2==0). Second, why are my evens out of order? 2 comes before 6 right? By analyzing this result, we'll learn something deeper about how the sorted() 'key' argument works, especially in conjunction with the anonymous lambda function.

Firstly, you'll notice that while the odds come before the evens, the evens themselves are not sorted. Why is this?? Lets read the docs:

Key Functions Starting with Python 2.4, both list.sort() and sorted() added a key parameter to specify a function to be called on each list element prior to making comparisons.

We have to do a little bit of reading between the lines here, but what this tells us is that the sort function is only called once, and if we specify the key argument, then we sort by the value that key function points us to.

So what does the example using a modulo return? A boolean value: True == 1, False == 0. So how does sorted deal with this key? It basically transforms the original list to a sequence of 1s and 0s.

[3,6,3,2,4,8,23] becomes [0,1,0,1,1,1,0]

Now we're getting somewhere. What do you get when you sort the transformed list?

[0,0,0,1,1,1,1]

Okay, so now we know why the odds come before the evens. But the next question is: Why does the 6 still come before the 2 in my final list? Well that's easy - its because sorting only happens once! i.e. Those 1s still represent the original list values, which are in their original positions relative to each other. Since sorting only happens once, and we don't call any kind of sort function to order the original even values from low to high, those values remain in their original order relative to one another.

The final question is then this: How do I think conceptually about how the order of my boolean values get transformed back in to the original values when I print out the final sorted list?

Sorted() is a built-in method that (fun fact) uses a hybrid sorting algorithm called Timsort that combines aspects of merge sort and insertion sort. It seems clear to me that when you call it, there is a mechanic that holds these values in memory and bundles them with their boolean identity (mask) determined by (...!) the lambda function. The order is determined by their boolean identity calculated from the lambda function, but keep in mind that these sublists (of one's and zeros) are not themselves sorted by their original values. Hence, the final list, while organized by Odds and Evens, is not sorted by sublist (the evens in this case are out of order). The fact that the odds are ordered is because they were already in order by coincidence in the original list. The takeaway from all this is that when lambda does that transformation, the original order of the sublists are retained.

So how does this all relate back to the original question, and more importantly, our intuition on how we should implement sorted() with its key argument and lambda?

That lambda function can be thought of as a pointer that points to the values we need to sort by, whether its a pointer mapping a value to its boolean transformed by the lambda function, or if its a particular element in a nested list, tuple, dict, etc., again determined by the lambda function.

Lets try and predict what happens when I run the following code.

mylist = [(3, 5, 8), (6, 2, 8), ( 2, 9, 4), (6, 8, 5)]
sorted(mylist, key=lambda x: x[1])

My sorted call obviously says, "Please sort this list". The key argument makes that a little more specific by saying, for each element (x) in mylist, return index 1 of that element, then sort all of the elements of the original list 'mylist' by the sorted order of the list calculated by the lambda function. Since we have a list of tuples, we can return an indexed element from that tuple. So we get:

[(6, 2, 8), (3, 5, 8), (6, 8, 5), (2, 9, 4)]

Run that code, and you'll find that this is the order. Try indexing a list of integers and you'll find that the code breaks.

This was a long winded explanation, but I hope this helps to 'sort' your intuition on the use of lambda functions as the key argument in sorted() and beyond.


lambda is a Python keyword that is used to generate anonymous functions.

>>> (lambda x: x+2)(3)
5

The variable left of the : is a parameter name. The use of variable on the right is making use of the parameter.

Means almost exactly the same as:

def some_method(variable):
  return variable[0]

lambda is an anonymous function, not an arbitrary function. The parameter being accepted would be the variable you're working with, and the column in which you're sorting it on.


Since the usage of lambda was asked in the context of sorted(), take a look at this as well https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions


One more example of usage sorted() function with key=lambda. Let's consider you have a list of tuples. In each tuple you have a brand, model and weight of the car and you want to sort this list of tuples by brand, model or weight. You can do it with lambda.

cars = [('citroen', 'xsara', 1100), ('lincoln', 'navigator', 2000), ('bmw', 'x5', '1700')]

print(sorted(cars, key=lambda car: car[0]))
print(sorted(cars, key=lambda car: car[1]))
print(sorted(cars, key=lambda car: car[2]))

Results:

[('bmw', 'x5', '1700'), ('citroen', 'xsara', 1100), ('lincoln', 'navigator', 2000)]
[('lincoln', 'navigator', 2000), ('bmw', 'x5', '1700'), ('citroen', 'xsara', 1100)]
[('citroen', 'xsara', 1100), ('lincoln', 'navigator', 2000), ('bmw', 'x5', '1700')]

Just to rephrase, the key (Optional. A Function to execute to decide the order. Default is None) in sorted functions expects a function and you use lambda.

To define lambda, you specify the object property you want to sort and python's built-in sorted function will automatically take care of it.

If you want to sort by multiple properties then assign key = lambda x: (property1, property2).

To specify order-by, pass reverse= true as the third argument(Optional. A Boolean. False will sort ascending, True will sort descending. Default is False) of sorted function.

참고URL : https://stackoverflow.com/questions/8966538/syntax-behind-sortedkey-lambda

반응형