Created
May 3, 2021 18:30
-
-
Save IvanFrecia/500d6e08b5da96e3babc3bba97a9b85e to your computer and use it in GitHub Desktop.
Data Collection and Processing with Python - Week 2 - 23.3 - Filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Now consider another common pattern: going through a list and keeping only those items that meet certain criteria. This is called a filter. | |
# Again, this pattern of computation is so common that Python offers a more compact and general way to do it, | |
# the filter function. filter takes two arguments, a function and a sequence. The function takes one item | |
# and return True if the item should. It is automatically called for each item in the sequence. You don’t | |
# have to initialize an accumulator or iterate with a for loop. | |
def keep_evens(nums): | |
new_seq = filter(lambda num: num % 2 == 0, nums) | |
return list(new_seq) | |
print(keep_evens([3, 4, 6, 7, 0, 1])) | |
# Output: | |
#[4, 6, 0] | |
# 1) Write code to assign to the variable filter_testing all the elements in lst_check that have a w in | |
# them using filter. | |
lst_check = ['plums', 'watermelon', 'kiwi', 'strawberries', 'blueberries', 'peaches', 'apples', 'mangos', 'papaya'] | |
filter_testing = filter(lambda word: "w" in word, lst_check) | |
print(filter_testing) | |
# Output: ['watermelon', 'kiwi', 'strawberries'] | |
# 2. Using filter, filter lst so that it only contains words containing the letter “o”. Assign to | |
# variable lst2. Do not hardcode this. | |
lst = ["witch", "halloween", "pumpkin", "cat", "candy", "wagon", "moon"] | |
lst2 = filter(lambda word: "o" in word, lst) | |
print(lst2) | |
# Output: ['halloween', 'wagon', 'moon'] |
lst_check = ['plums', 'watermelon', 'kiwi', 'strawberries', 'blueberries', 'peaches', 'apples', 'mangos', 'papaya']
filter_testing = list(filter(lambda have_w: 'w' in have_w , lst_check))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
lst = ["witch", "halloween", "pumpkin", "cat", "candy", "wagon", "moon"]
lst2 = list(filter(lambda have_o: 'o' in have_o , lst ))