Python-for-Data-Analysis|3.2 函数

E7phpF.png

Functions

如果函数不带有返回值,那么会自动返回一个None

每个函数都含有位置参数和关键字参数,关键字参数通常指明了默认值。下面例子中的z=0.7就是关键字参数。

1
2
3
4
5
def my_function(x, y, z=1.5):
if z > 1:
return z * (x + y)
else:
return z / (x + y)
1
2
3
my_function(5, 6, z=0.7)
my_function(3.14, 7, 3.5)
my_function(10, 20)
45.0

Namespaces,Scope,and Local Functions

在函数体中的变量为局部变量,函数被调用时,局部命名空间(local namespaces)被创建,但函数结束时被释放。

Returning Multiple Values

返回多个值的原理:实际上返回的是一个tuple,这些元组被unpack后赋给不同的变量

1
2
3
4
5
6
7
def f():
a = 5
b = 6
c = 7
return a, b, c

a, b, c = f()
1
2
return_value=f()
print(return_value)
(5, 6, 7)

Functions Are Objects

可以用列表函数的方法作用于指定的对象

1
2
states = ['   Alabama ', 'Georgia!', 'Georgia', 'georgia', 'FlOrIda',
'south carolina##', 'West virginia?']
1
2
3
4
5
6
7
8
9
10
11
12
13
import re
def remove_punctuation(value):
return re.sub('[!#?]', '', value)

clean_ops = [str.strip, remove_punctuation, str.title]

def clean_strings(strings, ops):
result = []
for value in strings:
for function in ops:
value = function(value)
result.append(value)
return result
1
clean_strings(states,clean_ops)
['Alabama',
 'Georgia',
 'Georgia',
 'Georgia',
 'Florida',
 'South   Carolina',
 'West Virginia']

你可以用函数作为map函数的参数,map的作用是将函数运用到某个序列中

1
2
for x in map(remove_punctuation, states):
print(x)
   Alabama 
Georgia
Georgia
georgia
FlOrIda
south   carolina
West virginia

Anonymous(Lambda) Functions

lambda关键字除了表示“我们申明了一个匿名函数”之外没有任何其他含义

1
2
3
4
5
def apply_to_list(some_list, f):
return [f(x) for x in some_list]

ints = [4, 0, 1, 5, 6]
apply_to_list(ints, lambda x: x * 2)
[8, 0, 2, 10, 12]

Currying:Partial Argument Application

柯里化(currying)是一个有趣的计算机科学术语,它指的是通过“部分参数应用”(partial argument application)从现有函数派生出新函数的技术。

Generators

用一致的方式在序列中进行迭代,是python的重要特征。这个过程是由迭代协议(iterator protocol),一种原始的使对象迭代的方法。

关于迭代器更多内容:for循环在Python中是怎么工作的

生成器延时返回一个序列,每返回一个值便暂停直到下一个值被请求。这和普通函数执行并且返回一个单一的值正好相反。

Errors and Exception Handing

python中的float函数用来把一个string类型的值转换成float,注意观察下面的第二个例子中的错误是一ValueError

1
float('1.2345')
1.2345
1
float('something')
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-22-2649e4ade0e6> in <module>
----> 1 float('something')


ValueError: could not convert string to float: 'something'

可以用except来处理错误信息。

1
2
3
4
5
def attempt_float(x):
try:
return float(x)
except (ValueError,TypeError):
return x

此外还有else:当try的内容成功执行后执行elsefinally:无论try是否成功执行,都会执行finally

-------------End-------------
梦想总是要有的,万一有人有钱呢?