Last active
October 30, 2019 13:45
-
-
Save etigui/23a641902a9a54c18361436105e94354 to your computer and use it in GitHub Desktop.
List comprehension vs. lambda + filter (json/SimpleNamespace)
This file contains hidden or 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
# Ref: https://stackoverflow.com/questions/3013449/list-comprehension-vs-lambda-filter/3013686 | |
# Ref json: https://catalog.data.gov/dataset/most-popular-baby-names-by-sex-and-mothers-ethnic-group-new-york-city-8c742 | |
from types import SimpleNamespace | |
import json | |
import time | |
data_object = {} | |
with open('name.json', 'r') as f: | |
json_data = f.read() | |
data_object = json.loads(json_data, object_hook=lambda d: SimpleNamespace(**d)) | |
filter_time = time.time() | |
list(filter(lambda f : f.name == 'Alessandra', data_object.data)) | |
print(f'Lambda + Filter time: {time.time() - filter_time}') | |
compr_time = time.time() | |
x = [c for c in data_object.data if c.name == 'Alessandra'] | |
print(f'Comp time: {time.time() - compr_time}') | |
# [OUTPUT] | |
# Lambda + Filter time: 0.0024056434631347656 | |
# Comp time: 0.0017428398132324219 | |
# [name.json] | |
# { | |
# "data": [ | |
# { | |
# "a": "row-v4f5~xz3v-vr86", | |
# "b": "00000000-0000-0000-E0ED-52E8592E0A7A", | |
# "c": 0, | |
# "d": 1425766822, | |
# "e": null, | |
# "f": 1425766822, | |
# "g": null, | |
# "h": "{ }", | |
# "i": "2011", | |
# "j": "FEMALE", | |
# "k": "HISPANIC", | |
# "name": "geraldine", | |
# "m": "13", | |
# "n": "75" | |
# }, | |
# { | |
# "a": "row-gdep~mr7x-dj3u", | |
# "b": "00000000-0000-0000-68AD-7B741D1DF31B", | |
# "c": 0, | |
# "d": 1425766822, | |
# "e": null, | |
# "f": 1425766822, | |
# "g": null, | |
# "h": "{ }", | |
# "i": "2011", | |
# "j": "FEMALE", | |
# "k": "HISPANIC", | |
# "name": "Alessandra", | |
# "m": "21", | |
# "n": "67" | |
# }] | |
# } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment