我正在尝试分类的键,并试图将lambdas与函数进行比较以尝试并了解lambdas的工作方式,以及如何将数据传递到lambda中的可替换参数。
>有人可以解释我尝试使用该函数而不是lambda时在这里做错了什么 - 似乎我假设参数如何传递到从排序键传递到lambda变量,如果使用功能。
请参阅下面的我的代码以及下面的输出...
这是我的代码:
#!/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
使用key=slice_2
,而不是key=slice_2(y)
。您需要使用函数本身作为键,而不是使用不存在的神秘y
调用该功能的结果。
您只需要将函数(名称)作为键,而不是任何(y)参数。该函数将自动以当前元素作为单参数调用。
sf = sorted(student_tuples, key=slice_2)
这应该给出预期的输出。