1.4 函数介绍
# 常用内置函数
a = [1, 2, 3, 4, 5]
element_max = max(a)
element_min = min(a)
element = round(4.2424451, 2) # 四舍五入
b = 'hello,world'
isinstance(b, str)
len(b)
c = ['one', 'two', 'three']
for i, j in enumerate(c): # 枚举
print(i, j)
list1 = ['a', 'b', 'c', 'd']
list2 = [1, 2, 3, 4]
e = list(zip(list1, list2))
# 第三方库
import math
math.floor(4.7) # 向下取整
math.ceil(4.7) # 向上取整
import numpy as np
np.min([1, 4, 6, 7])
np.argmin([1, 4, 6, 7])
# 自定义函数
def exponent(a, b):
x = a ** b
return x
def ssn(n, beg=1):
s = 0
for i in range(beg, n+1):
s += i
return s
1.5 字符串处理
具体可查看:https://www.runoob.com/python/python-strings.html
# 字符串格式化
print('我今年%s岁,目前薪水%s以上' % (30, '2万'))
print('我今年{:.2f}岁,目前薪水{}以上'.format(30, '2万'))
# 大小写转换
filed = 'This is me'
filed.upper()
filed.capitalize()
# 去空格
tele = ' This is me '
tele.strip()
tele.rstrip()
tele.lstrip()
# 判断是不是全是数字
tele.isdigit()
# 判断是不是以参数开头
tele.startswith(' This')
# 判断是不是由数字和字母构成的
tele.isalnum()
# 统计次数
tele.count('i')
1.6 高级函数
(1)lambda函数(匿名函数)
匿名函数:
- 不需要使用def来定义,使用lambda来定义函数
- 没有具体名称
- 语法结构:lmbda par1,par2,···parn:expression
g = lambda x: x**2
a = g(2)
f1 = lambda x: 'A' if x == 1 else 'B'
b = f1(100) # B
c = f1(1) # A
total = lambda x, y, z: x+2*y+3*z
d = total(1, 2, 3)
(2)map函数
def f(x):
return x**2
items = [1, 2, 3, 4, 5, 6]
a = list(map(f, items))
b = list(map(lambda x: x**2, items))
(3)reduce函数
from functools import reduce
def f(x,y):
return x+y
items = range(1, 101, 1)
result = reduce(f, items)
map和reduce强大在于联系在一起用,如:reduce(func2,map(func1,iter))
(4)filter函数
- 语法结构:filter(function, sequnce)
- 用于过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的序列
- 将function依次作用于sequnce的每个item,即function(item),将返回值为True的item组成一个list、string、tuple(取决于sequnce的类型)
a = list(filter(lambda x: x % 2 == 0, range(21)))
items = [1, 2, 3, 4, '3234', 'ine', '-34.56', 45.8, -7]
b = list(filter(lambda x: 1 if isinstance(x, int) else 0, items))
def int_num(x):
if isinstance(x, int):
return True
else:
return False
c = list(filter(int_num, items))