2017-02-22 2 views
0

나는 정렬 된 키를 실험하고 함수와 람다를 비교하려고한다. 시도하고 어떻게 람다가 작동하는지 이해하고, 정렬 된 방법으로 데이터를 람다의 대체 가능한 매개 변수로 전달합니다.python (버전 2.7.12 우분투 16.04.1에) - 함수 (2를 반환하는 람다와 유사)가 정렬 키로 작동하지 않는다

람다 대신 함수를 사용하려고하면 누군가 내가 뭘 잘못했는지 설명해 주실 수 있습니까? 사용하는 경우 매개 변수가 정렬 된 키의 람다 변수로 전달되는 방식에 대한 내 가정처럼 보입니다. 함수. 여기

#!/usr/bin/python #-------------------------- sep = "\n----------------\n" #-------------------------- student_tuples = [ ('john', 'A', 15), ('jane', 'C', 10), ('dave', 'D', 12), ] #-------------------------- print sep, "plain student_tuples on each line" for x in student_tuples: print x, type(x) #-------------------------- print sep, "show lambda is returning element 2 of each nested tuple" for line in student_tuples: ld = (lambda x: x[2])(line) print ld, type(ld) #-------------------------- print sep, "show sorted is passing each tuple to lambda in key=" st = sorted(student_tuples, key=lambda x: x[2]) for s in st: print s # the above suggests (to me), that key=whatever in sorted is passing # each element (or nested tuple) from the parent tuple # into the replacable x parameter of the lambda, (which returns element 2.) # # therefore, I should be able to replace the lambda with a function # that does the same thing, and the key= part of sorted should pass # each tuple to the replacable paramter of the function too. #-------------------------- # define a function that should do the same as the lambda def slice_2(a): return a[2] #-------------------------- print sep, "function, slice_2 on its own for student_tuples" for line in student_tuples: s2 = slice_2(line) print s2, type(s2) #-------------------------- print sep, "sorted should pass data into slice_2 functions replacable paramter" sf = sorted(student_tuples, key=slice_2(y)) for l in sf: print l #-------------------------- ################# # end of script # ################# 

는 예외 오류와 스크립트의 출력 :

내 아래 코드와 그 아래의 출력을 참조하십시오은 ... 여기

내 코드입니다

---------------- 
plain student_tuples on each line 
('john', 'A', 15) <type 'tuple'> 
('jane', 'C', 10) <type 'tuple'> 
('dave', 'D', 12) <type 'tuple'> 

---------------- 
show lambda is returning element 2 of each nested tuple 
15 <type 'int'> 
10 <type 'int'> 
12 <type 'int'> 

---------------- 
show sorted is passing each tuple to lambda in key= 
('jane', 'C', 10) 
('dave', 'D', 12) 
('john', 'A', 15) 

---------------- 
function, slice_2 on its own for student_tuples 
15 <type 'int'> 
10 <type 'int'> 
12 <type 'int'> 

---------------- 
sorted should pass data into slice_2 functions replacable paramter 
Traceback (most recent call last): 
    File "./compare-tuple-to-function.py", line 88, in <module> 
    sf = sorted(student_tuples, key=slice_2(y)) 
NameError: name 'y' is not defined 

답변

2

key=slice_2, n o key=slice_2(y). 함수 자체가을 키로 사용해야하며, 존재하지 않는 신비한 y과 함께 호출되는 함수 결과는 아닙니다.

+0

안녕하세요. Stefan, 답변 해 주셔서 대단히 감사합니다. 그것은 지금 올바르게 작동합니다. – Brad

0

키 (y) 매개 변수가 아닌 함수 (이름) 만 입력하면됩니다. 이 함수는 현재 요소를 단일 매개 변수로 사용하여 자동으로 호출됩니다.

sf = sorted(student_tuples, key=slice_2) 

예상되는 출력을 제공해야합니다.

+0

안녕하세요, 크리스챤, 당신의 답변에 감사드립니다. .... 나는이 상황에서 함수 구문이 "key = slice_2"일 필요가 있다는 것을 몰랐다. (다른 곳에서는 "result = slice_2 (y) syntax"를 사용하는 것과는 다릅니다.) - 저는 파이썬으로 학습 곡선을 잡았습니다 .... 두 분 모두에게 감사드립니다. – Brad

+0

차이점은 다음과 같습니다 : slice_2 (y)는 함수를 호출합니다. 그런 다음 값을 반환합니다. 그래서 보통'result = slice_2 (y)'를 할 때 함수의 반환 값을 단순히 변수 result에 할당합니다. 그러나 여기에서는 특정 반환 값을 원하지 않습니다. 대신 sorted() 함수에 순서를 지정하는 데 사용할 수있는 함수를 제공하려고합니다. 하지만 예, 이것은 처음에는 이상하게 보일 수 있습니다. –

+1

설명하기 전에 key =가 어떻게 함수에 매개 변수를 전달했는지 생각했습니다. 이제는 key = func 또는 key = lambda를 이해 했으므로 함수 또는 람다를 정렬에 전달하고 있습니다. 이는 근본적인 차이입니다. (그래서 나는 키 = 어떤 일을 시도하고 이해하는지 노력할 가치가 있었다). 다시 한 번 감사드립니다! – Brad