Skip to content

Instantly share code, notes, and snippets.

@codenameyau
Last active June 29, 2017 15:34
Show Gist options
  • Save codenameyau/91d9c4c747eec34b4906 to your computer and use it in GitHub Desktop.
Save codenameyau/91d9c4c747eec34b4906 to your computer and use it in GitHub Desktop.
Python lambda vs list comprehension
################################################################
# BASICS: LAMBDA VS LIST COMPREHENSION
################################################################
# Filter
filter(lambda x: x % 2, range(10))
[x for x in range(10) if x % 2]
# Map
map(lambda x: x*x, range(10))
[x*x for x in range(10)]
# Reduce
reduce(lambda x, y: x+y, range(10))
sum(range(10))
################################################################
# CHAIN IT UP
################################################################
# Chain: level 1
map(lambda x: x*x, filter(lambda x: x % 2, range(10)))
[x*x for x in range(10) if x % 2]
# Chain: level 2
reduce(lambda x, y: x+y, map(lambda x: x*x, filter(lambda x: x % 2, range(10))))
sum([x*x for x in range(10) if x % 2])
################################################################
# Filters
################################################################
# Filters out None truthty values
L = [1, False, [], (), 42, None, True]
filter(bool, L)
@codenameyau
Copy link
Author

Python Logging

import sys, logging
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler = logging.StreamHandler(stream=sys.stdout)
handler.setFormatter(formatter)

file_handler = logging.FileHandler('migrate_study_to_postgres.log')
log.addHandler(handler)
log.addHandler(file_handler)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment