函数
1.命名
In [1]:
def func(x):
if x>10:
print('more than 10')
else:
print('less than 10')
In [2]:
func(2)
less than 10
函数可以将功能封装,以便下次继续使用。一般要加入数据类型的判断,以免报错。
In [3]:
def add(x,y):
print(x+y)
In [4]:
a = add(1,2)
3
In [5]:
a
并没有对a进行赋值。print的值是无法使用的。
In [7]:
def add(x,y):
return x+y
In [8]:
c = add(1,2)
In [9]:
c
Out[9]:
3
c已经进行了赋值。
例:简单的四则运算函数
In [15]:
def arith(x,y,method):
if method == 'plus':
return x+y
elif method == 'minus':
return x-y
elif method == 'time':
return x*y
elif method == 'divide':
return x/y
else:
print('error method!')
In [16]:
arith(1,2,'divide')
Out[16]:
0.5
赋值参数
默认运算为加法
In [17]:
def arith(x,y,method = 'plus'):
if method == 'plus':
return x+y
elif method == 'minus':
return x-y
elif method == 'time':
return x*y
elif method == 'divide':
return x/y
else:
print('error method!')
In [18]:
arith(1,10)
Out[18]:
11
列表+函数
In [19]:
def desc(list):
size = len(list)
avg = sum(list)/size
#计算中位数
list.sort()
if size % 2 == 0:
mid = (list[size//2-1]+list[size//2])/2
else:
mid = list[(size-1)//2]
print('max is ',max(list))
print('min is ',min(list))
print('avg is ',avg)
print('mid is ',mid)
In [21]:
desc([i for i in range(1,100,4)])
max is 97
min is 1
avg is 49.0
mid is 49
高阶函数
map函数:全匹配,把某种特性或功能赋予所有的值
In [22]:
def func(x):
return x*x
In [23]:
[func(i) for i in range(1,5)]
Out[23]:
[1, 4, 9, 16]
用map函数来实现
In [24]:
map(func,[1,2,3,4,5])
Out[24]:
<map at 0x67539e8>
In [27]:
list(map(func,[1,2,3,4]))
Out[27]:
[1, 4, 9, 16]
两者实现了同样的功能
lambda 匿名函数
In [28]:
lambda x:x*x
Out[28]:
<function __main__.<lambda>>
In [29]:
list(map(lambda x:x*x,[1,2,3,4]))
Out[29]:
[1, 4, 9, 16]
第三方包
In [30]:
import collections
In [31]:
a = [1,2,3,1,2,31,2,1]
In [33]:
dict(collections.Counter(a))
Out[33]:
{1: 3, 2: 3, 3: 1, 31: 1}
将要学习的第三方包如下
In [34]:
import collections
import csv
import datetime
import math
In [35]:
import pandas
import numpy
Numpy
In [36]:
import numpy as np
In [37]:
np.array([1,2,3,4]) #转换成数组
Out[37]:
array([1, 2, 3, 4])
In [38]:
type(np.array([1,2,3,4])) #nd n维数组结构
Out[38]:
numpy.ndarray
In [39]:
a = np.array([1,2,3,4])
In [40]:
a[0] = 5
In [41]:
print(a)
[5 2 3 4]
In [42]:
a + a
Out[42]:
array([10, 4, 6, 8])
In [43]:
a * 2
Out[43]:
array([10, 4, 6, 8])
两种表现形式对比,array的表现形式更像一个矩阵。
In [52]:
b = np.array([[1,2,3,4],[5,6,7,8],[5,6,7,8]])
print(b)
[[1 2 3 4]
[5 6 7 8]
[5 6 7 8]]
In [48]:
[[1,2,3,4],[5,6,7,8],[5,6,7,8]]
Out[48]:
[[1, 2, 3, 4], [5, 6, 7, 8], [5, 6, 7, 8]]
In [50]:
b[1][0]
Out[50]:
5
In [51]:
b.dtype #numpy的数据类型一般是int32或float64
Out[51]:
dtype('int32')