Я экспериментирую с отсортированными ключами и пытаюсь сравнить lambdas с функциями чтобы попытаться понять, как работают лямбды, и как сортировка передает данные в заменяемые параметры в лямбда.python (версия 2.7.12 на ubuntu 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
Привет, Стефан, большое спасибо за ваш ответ. Теперь он работает правильно. – Brad