Может ли кто-нибудь объяснить, почему сравнение в операторе if выглядит иначе, когда один и тот же оператор используется в лямбда-выражении?
Учитывая приведенный ниже код, я предположил, что сравнение оператора if исключит 18, если только явно включено с использованием <=
.
Одной мыслью было то, что функция def явно возвращает True
или False
, но я не проверял это.
Что следует Я знаю об этом фундаментальном поведении, чтобы избежать путаницы?
Если это имеет значение, Python 3.6.9.
ages = [5, 12, 17, 18, 24, 32]
def fn(x):
if x < 18:
return False
else:
return True
# the key function is the first argument to 'filter', and the second is the list input 'ages'
# below, the lambda does not directly input the list, 'filter' picks up 'ages' and iterates to 'lambda', but, strangely, there is a difference of interpretation in the output between the def's if statement and the lambda key function in the use of comparison operators???
adults = filter(fn, ages)
print(list(adults))
# list is returned by way of list() wrapped expression
adults = list(filter(lambda _: (_>18), ages))
print(adults)
Какие выходы:
def: [18, 24, 32]
lambda: [24, 32]