Skip to content

Instantly share code, notes, and snippets.

@dosht
Created August 30, 2014 19:07
Show Gist options
  • Save dosht/3b45123360940857aef9 to your computer and use it in GitHub Desktop.
Save dosht/3b45123360940857aef9 to your computer and use it in GitHub Desktop.
Which way do you prefer?
# Partition the following data into 2 lists: males and females
users = [{
"name": "user_%s" % x,
"gender": 'f' if x % 3 is random.randint(0,3) else 'm'
}
for x in range(1, 100)]
# Which way do you prefer?
# 1
males, females = [], []
for user in users:
if user['gender'] is 'm':
males.append(user)
if user['gender'] is 'f':
females.append(user)
# 2
males = [u for u in users if u['gender'] is 'm']
females = [u for u in users if u['gender'] is 'f']
# 3
def reduce_func((males, females), user):
if user['gender'] is 'f':
return (males, females + [user])
if user['gender'] is 'm':
return (males + [user], females)
return (males, females)
(males, females) = reduce(reduce_func, users, ([], []))
# 4
(males, females) = reduce(
lambda (ms, fs), u:
(ms, fs + [u]) if u['gender'] is 'f' else (ms + [u], fs) if u['gender'] is 'm' else (ms, fs),
users,
([], []))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment