0
takewhile() and filter() does the same job. What is the difference between the two ?
If even there's 1, when to use which function ? Someone please explain...
3 Respostas
+ 3
The main difference is that, takewhile exits as soon as the criterion fails. Run the code below to see the difference.
from itertools import accumulate, takewhile
nums = [1, 9, 2, 3, 6, 7]
print(nums)
print(list(takewhile(lambda x: x%2 != 0, nums)))
print(list(filter(lambda x: x%2 != 0, nums)))
0
i think the only difference is dat takewhile should b imported before use but filter cn b used directly
0
In the playground, I get the error "Uncaught SyntaxError: Unexpected identifier"
Even the 2nd line: nums = [1,...] shows a red x before I run.
Is this happening because playground can't import from itertools? Or, is it something else?