It's a little bit difficult to figure out exactly what you're trying to do. I'm going to interpret your question, then provide an answer. If this is not correct, please modify your question or comment on this answer.
Question
I have sequences that are exactly three elements long. Here's one:
sequence1 = [1, 4, 8]
I want to ensure that the first element is less than the second element, which should in turn be less than the third element. I've written the following function to do so:
max_validation = lambda x, y, z: x < y < z
How do I apply this using filter
? Using filter(max_validation, sequence1)
doesn't work.
Answer
Filter applies your function to each element of the provided iterable, picking it if the function returns True
and discarding it if the function returns False
.
In your case, filter
first looks at the value 1
. It tries to pass that into your function. Your function expects three arguments, and only one is provided, so this fails.
You need to make two changes. First, put your three-element sequence into a list or other sequence.
sequences = [[1, 4, 8], [2, 3, 9], [3, 2, 3]]
max_validation = lambda x: x[0] < x[1] < x[2] and len(x) == 3
I've added two other sequences to test. Because sequences
is a list of a list, each list gets passed to your test function. Even if you're testing just one sequence, you should use [[1, 4, 8]]
so that the entire sequence to test gets passed into your function.
I've also modified max_validation
so that it accepts just one argument: the list to test. I've also added and len(x) == 3
to ensure that the sequences are only 3 elements in length