나는 정렬 된 키를 실험하고 함수와 람다를 비교하려고한다. 시도하고 어떻게 람다가 작동하는지 이해하고, 정렬 된 방법으로 데이터를 람다의 대체 가능한 매개 변수로 전달합니다.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
안녕하세요. Stefan, 답변 해 주셔서 대단히 감사합니다. 그것은 지금 올바르게 작동합니다. – Brad