Table of Contents
This guide covers filter ()() function in python with practical context and easy-to-follow details. Use it to understand the subject and apply the information confidently.
filter(func, iterable)
The filter () function has 2 parameters:
- Func: Is a conditional function to check whether the elements in Interable Are true or false, Func Can only return True or False.
- Interable: Is iterable to filter, can be set, list, tuple or container.
# danh sách ch? cáialphabet = ['a', 'b', 'd', 'e', 'i', 'j', 'o']# l?c nguyên âm# vi?t b?i TipsMake.comdef filterNguyenam(alphabet):nguyenam = ['a', 'e', 'i', 'o', 'u']if(alphabet in nguyenam):return Trueelse:return FalsefilterNguyenam = filter(filterNguyenam, alphabet)print('Các nguyên âm ???c l?c là:')for nguyenam in filterNguyenam:print(nguyenam)
Run the program, the result is:
Các nguyên âm ???c l?c là:aeio
Here, we list a list of letters and need to filter out vowels in it.
You can use a for loop to test each component in the list and store it to another list, but using Python the process will be easier and faster by using the filter method (). .
# random list# vi?t b?i TipsMake.comrandomList = [1, 'a', 0, False, True, '0']filteredList = filter(None, randomList)print('Các ph?n t? ???c l?c là:')for element in filteredList:print(element)
Run the program, the result is:
Các ph?n t? ???c l?c là:1aTrue0
Here, we have a random list of numbers, strings and boolean called randomList. We pass randomList to the filter () function with the first parameter (func) being None. At this point, the function itself becomes Identity function by default, so we get TRUE elements 1, a, True and '0' ('0' in string form).
Previous article: Function hasattr () in Python
Next lesson: int () function in Python
FAQ
What should I check before following these steps?
Confirm device and software compatibility, save important data, and make sure you have the required permissions, files, and account access.
Why might the process not work?
Common causes include outdated software, missing permissions, incompatible hardware, an unstable connection, or completing a step in the wrong order.
Can I undo the changes if necessary?
That depends on the tool or setting. Use built-in restore options when available, keep a backup, and record the original configuration first.
Reader Comments 0
Sign in with email or Google to join the discussion.