Created
December 4, 2014 19:01
-
-
Save bikz05/eabb0a730bf47d1654d0 to your computer and use it in GitHub Desktop.
Python Idioms
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
# zip([iterable, ...]) | |
# This function returns a list of tuples, | |
# where the i-th tuple contains the i-th | |
# element from each of the argument sequ- | |
# ences or iterables. | |
a = [1, 2, 3, 4, 5, 6]; | |
b = [6, 5, 4, 3, 2, 1]; | |
c = [cA*cB for cA, cB in zip(a, b)]; # c = [6, 10, 12, 12, 10, 6] | |
# Sorting using keys | |
# More at https://wiki.python.org/moin/HowTo/Sorting | |
d = [-2, -23, 32, -3, 0, -34]; | |
print sorted(d, key = lambda x:abs(x), reverse = True); | |
# OUTPUT = [-34, 32, -23, -3, -2, 0] | |
# map(function, iterable, ...) | |
# Apply function to every item of iterable | |
# and return a list of the results. | |
print map(hash, b); # This will hash all the ints in b | |
# lambda - creating anonymous inline functions | |
print (lambda x, y: x*y)(3, 4); # OUTPUT = 4 | |
incrementer = lambda input: input + 1; | |
# above is same as def incrementer(input): return input+1 | |
# now we call it | |
print incrementer(3); # OUTPUT = 12 | |
# lambda and map together | |
squares = map(lambda x: x**2, range(10)); | |
print squares # OUTPUT = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] | |
# filter | |
# Filter takes a function returning True or False and applies | |
# it to a sequence, returning a list of only those members of | |
# the sequence for which the function returned True. | |
special_squares = filter(lambda x: x > 5 and x < 50, squares); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment