Skip to content

Instantly share code, notes, and snippets.

@MocoNinja
Created September 22, 2021 07:33
Show Gist options
  • Save MocoNinja/f30a3c8a2e1a6db265a3086c46c6619c to your computer and use it in GitHub Desktop.
Save MocoNinja/f30a3c8a2e1a6db265a3086c46c6619c to your computer and use it in GitHub Desktop.
Python Filter | Map | Reduce Quick Reminder
#!/usr/bin/python3
# -*- encoding: utf-8 -*-
import logging as log
from functools import reduce
log.basicConfig(level=log.INFO)
def main():
"""
Simple filter + list comprehension
"""
filtered_list = list(filter((lambda x: x % 2 == 0),
[x for x in range(0, 10001)]))
log.info(f"There are {len(filtered_list)} even numbers from 0 to 10000")
"""
Sample data
"""
pilots = [
{
"id": 10,
"name": "Poe Dameron",
"years": 14,
},
{
"id": 2,
"name": "Temmin 'Snap' Wexley",
"years": 30,
},
{
"id": 41,
"name": "Tallissan Lintra",
"years": 16,
},
{
"id": 99,
"name": "Ello Asty",
"years": 22,
}
]
"""
Simple filter from data
"""
teen_pilots = list(filter((lambda pilot: pilot['years'] < 18), pilots))
for pilot in teen_pilots:
log.info(f"{pilot} is a teenager...")
"""
Simple data transformation
"""
pilot_information = list(map(
(lambda pilot: f"Pilot '{pilot['name']} is {pilot['years']} years old..."), pilots))
for name in pilot_information:
log.info(name)
"""
Filter from transformed data
"""
not_teen_pilots_information = list(map((lambda pilot: f"{pilot['name']} is NOT a teenager"), filter(
(lambda pilot: pilot['years'] >= 18), pilots)))
for pilot_info in not_teen_pilots_information:
log.info(f"{pilot_info}")
"""
Reduce transformed data (not chained)
"""
pilot_ages = list(map((lambda pilot: pilot['years']), pilots))
total_age = reduce((lambda p1, p2: p1 + p2), pilot_ages)
log.info(f"The total age for those pilots is {total_age} years!")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment