Skip to content

Instantly share code, notes, and snippets.

@zenloner
zenloner / apply.py
Created April 10, 2013 04:47
use apply function to dynamicly run functions
func = lambda x, y, z: x+y+z
#tuple can be decompsed into prameters
apply(func, (1,2,3)) #it will return 6
def echo(*args, **kwargs): print args, kwargs
pargs = (1,2)
#dictionary can be decompsed into key-value pair parameters
kargs = {'a':3, 'b':4}
counters = [1, 2, 3, 4]
inc = lambda x: x+1
map(inc, counters) # it will return [2, 3, 4, 5]
#this is the same as [x+1 for x in counters], but map function is faster.
addt = lambda x, y, z: x+y+z
a = [1, 2, 3]
b = [1, 2, 3]
c = [1, 2, 3]
d = map(addt, a, b, c) # it will return [3, 6, 9]
filter((lambda x: x>0), range(-5, 5)) #result is [1, 2, 3, 4]
reduce((lambda x, y: x+y), [1, 2, 3, 4]) # result is 10
reduce((lambda x, y: x*y), [1, 2, 3, 4]) # result is 24
a = [1]
b = reduce((lambda x, y: x+y), a)
c = reduce((lambda x, y: x*y), a)
print b # print 1
print c # print 1
# map method
res = map(ord, 'spam')
# list comprehension method
res1 = [ord(x) for x in 'spam']
@zenloner
zenloner / list_comprehension1.py
Created April 10, 2013 05:14
add if test to list comprehension
res = [x for x in range(5) if x%2==0]
res1 = filter((lambda x: x%2==0), range(5))
print res
print res1
res = map((lambda x: x**2), filter((lambda x: x%2==0), range(5)))
res1 = [x**2 for x in range(5) if x%2==0]
print res
print res1
[ expression for target1 in sequence1 [if condition]
for target2 in sequence2 [if condition]
for target3 in sequence3 [if condition]
for target4 in sequence4 [if condition]
...
]
res = [x+y for x in [0, 1, 2] for y in [100, 200, 300]]
print res #[100, 200, 300, 101, 201, 301, 102, 202, 302]
res1 = [(x, y) for x in range(5) if x%2==0 for y in range(5) if y%2!=0]
print res1 #[(0, 1), (0, 3), (2, 1), (2, 3), (4, 1), (4, 3)]