argument
可以是scalar type, 也可以是list等data structure,可以是function
object都可以
Positional arguments and keywords argument
In [3]:
def my_function(x,y,z = 1.5):
if z>1:
return z*(x+y)
else:
return z/(x+y)
my_function(5,6,z = 0.7),my_function(3.14,7,3.5)
Out[3]:
(0.06363636363636363, 35.49)
Namespace, Scope, Local Functions
没有太多意思, 注意变量的存在范围, 以及在函数内部也可以定义函数
In [4]:
returning Multiple Values
def f():
a = 5
b = 6
c = 7
return a,b,c #returning a tuple
a,b,c = f()
print a,b,c
5 6 7
function are objects
we can use get a collection of fuctions using their names, they can be used as arguments
b = foo is an assignment
In [6]:
def addOne(x):
return x+1
def multiTwo(x):
return x*2
def minusTwo(x):
return x-2
def devTwo(x):
return x/2
def clear(x,ops):
for function in ops:
x = function(x)
return x
clear(5,[addOne,multiTwo,minusTwo,devTwo])
Out[6]:
5
lambda functions
关键词,lambda
In [9]:
#if we want to sort string using the number of unique characters
strings = ['abc','aaab','aaaaa']
strings.sort(key = lambda x: len(set(list(x))))
strings
Out[9]:
['aaaaa', 'aaab', 'abc']
Closures: Functions that Return Functions
暂时用不到
Extended Call Synatx with *args, **kw args
暂时用不到
Currying: Partial Argument Application
可以简化给定的函数
#在pandas处理时可能用到
#ma60 = lambda x:pandas.rolling_mean(x,60)
#data.apply(m60)
Generators
Itertools module
Files and Operating system
通常情况下, 用pandas.read_csv() to read data files into Python Data Structure