[008]Python的函数_内置函数和匿名函数_全栈基础

您好!此笔记的文本和代码以网盘形式分享于文末!

因个人能力有限,错误处欢迎大家交流和指正!基础部分内容简单,但多且零散!

python内置函数和匿名函数
内置函数:截止到py3.6,python提供了68个内置函数
匿名函数:为了解决那些功能很简单的需求而设计的一句话函数 lambda
用法栗子结果
作用域相关
globals
locals
a = 16
b = 'aB'

def test():
    c = 12
    d = 'aB'
    li1 = [c, d]
    for i in range(10):
        ret1 = i + 10
    # 基于字典形式获取locals所在命名空间的局部变量
    print(locals())

test()
# 基于字典形式获取全局变量globals
print(globals())
{'ret1': 19, 'i': 9, 'li1': [12, 'aB'], 'd': 'aB', 'c': 12}
{'__name__': '__main__', '__doc__':………………
字符串类型
代码的执行
# eval 将字符串类型的代码执行并返回结果
print(eval('1+2+3+4'))
# exec 将字符串类型的代码执行但不返结果
print(exec("1+2+3+4"))
exec("print('hello,world')")
10
None
hello,world
将字符串类型
的代码编译
compile
# 流程语句使用exec
code1 = 'for i in range(0,3): print (i)'
compile1 = compile(code1, '', 'exec')
exec(compile1)
# 求值表达式用eval
code2 = '1 + 2 + 3 + 4'
compile2 = compile(code2, '', 'eval')
print(eval(compile2))
# 交互语句使用single
code3 = 'name = input("please input your name:")'
compile3 = compile(code3, '', 'single')
exec(compile3)
print(name)
0
1
2
10
please input your name:Sinba
Sinba
输入输出
input
s = input('请输入名字:')
print(s, type(s))
请输入名字:Simba
Simba <class 'str'>
输入输出
print
"""
输出函数print
def print(self, *args, sep=' ', end='\n', file=None):
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    file:  默认是输出到屏幕,如果设置为文件句柄,输出到文件
    sep:   打印多个值之间的分隔符,默认为空格
    end:   每一次打印的结尾,默认为换行符
    flush: 立即把内容输出到流文件,不作缓存
"""
f = open('tmp_file', 'w')
print(123, 456, sep=',', file=f, flush=True)
创建 名为 tmp_file 的文件
且写入123,456
判断数据的类型
type
a = 15
print(type(a))
<class 'int'>
内存相关
id() 查内存地址
hash
# 查看对象的内存地址
b = 16
print(id(b))
# hash() 返回一个可hash变量的哈希值,
# 不可哈希的变量被hash则报错
tu1 = (1, 2, 3,)
print(hash(tu1))
1743744496
2528502973977326415
文件操作相关
open
open()  打开一个文件,返回一个文件操作符(文件句柄) 
模块操作相关os = __import__('os')
print(os.path.abspath('.'))
E:\pytext\002
帮助方法
help()
# 查看和参数对象有关的操作
help(str)
help(list)
 
和调用相关
callable(o)
# 查看参数对象是不是可被调用
def func():
    pass

print(callable(func))
print(callable(123))
True
False
产看参数类型
的内置方法
# 查看参数所属类型的所有内置方法
print(dir(list))
print(dir(tuple))
 
数字相关
类型相关
# 数据类型转换bool,int,float,complex等
a = True
b = str(a)
c = int(a)
d = float(a)
e = bool(b)
print(a, type(a))
print(b, type(b))
print(c, type(c))
print(d, type(d))
print(e, type(e))
True <class 'bool'>
True <class 'str'>
1 <class 'int'>
1.0 <class 'float'>
True <class 'bool'>
数字相关
进制转换
# 进制转换相关:bin,oct,hex
a = 15
b = bin(a)
c = oct(a)
d = hex(a)
print(a, b, c, d)
15 0b1111 0o17 0xf
数字相关
数学运算
# abs 计算绝对值
a = -15
print(abs(a))
# divmod 返回除数和余数
ret1, ret2 = divmod(15, 2)
print('除数是', ret1, '余数是', ret2)
# round 浮点数x的四舍五入值
print("round(7.23456) : ", round(7.23456))
print("round(6.659,1) : ", round(6.659,1))
print("round(8.265, 2) : ", round(8.264, 2))
print("round(10.001056, 3) : ", round(10.001056, 3))
print("round(-10.000056, 3) : ", round(-10.000056, 3))
# pow 幂运算pow(x, y) 方法返回(x的y次方)的值
a = 2
print("pow(2,3):", pow(a, 3))
# sum 求和 sum(iterable[, start])
# iterable -- 可迭代对象,如:列表、元组、集合
print("3+4 = ", sum([3, 4]))
# min 比较最小值
print('3和5 值小的:', min(3, 5))
# max 比较最大值
print('3和5 值大的:', max(3, 5))
15
除数是 7 余数是 1
round(7.23456) :  7
round(6.659,1) :  6.7
round(8.265, 2) :  8.26
round(10.001056, 3) :  10.001
round(-10.000056, 3) :  -10.0
pow(2,3): 8
3+4 =  7
3和5 值小的: 3
3和5 值大的: 5
数据结构相关
序列--列表元组
# 序列--列表和元组相关 list和tuple
tu1 = (123, 'baidu', 'a2C7')
s1 = 'Hello'
print('列表化:', list(tu1))
print('列表化:', list(s1))

li1 = [1, '2C', '123', 1]
s2 = 'world'
print('元组化:', tuple(li1))
print('元组化:', tuple(s2))
列表化: [123, 'baidu', 'a2C7']
列表化: ['H', 'e', 'l', 'l', 'o']
元组化: (1, '2C', '123', 1)
元组化: ('w', 'o', 'r', 'l', 'd')
数据结构相关
序列--字符串
# str
li1 = [1, '12A', 'aK7h']
ret1 = str(li1)
print("字符串化:", ret1, type(ret1))
字符串化: [1, '12A', 'aK7h'] <class 'str'>
数据结构相关
序列--字符串
# format 字符串格式化
a = 3.1415926
b = format(a)
print(b, type(b))
# format 指定对齐方式
print(format('test', '<20'))
print(format('test', '>20'))
print(format('test', '^20'))
# format 进制转换
# 'b' 'c' 'd' 'o' 'x' 'X' 'n' None
print(format(21, 'b'))
print(format(21, 'c'))  # 转换unicode成字符
print(format(21, 'X'))
# format 浮点数参数
# 科学计数法,默认保留6位小数
print(format(314159267, 'e'))
print(format(314159267, '0.2E'))
# 小数点计数法,默认保留6位小数
print(format(314159267, 'f'))
print(format(314159267, '0.5f'))
# g的格式化比较特殊
# 有需求访问https://www.cnblogs.com/Eva-J/articles/7266245.html
# p=1,exp=-5 ==》 -4<=exp<p不成立,按科学计数法计数,保留0位小数点
print(format(0.00003141566, '.1g'))
# p=1,exp=0 ==》 -4<=exp<p成立,按小数计数法计数,保留2位小数点
print(format(3.1415926777, '.3g'))
3.1415926 <class 'str'>
test               
                test
        test       
10101
 
15
3.141593e+08
3.14E+08
314159267.000000
314159267.00000
3e-05
3.14
数据结构相关
序列--字符串
# bytes 函数返回一个新的 bytes
# 对象该对象是一个 0 <= x < 256 区间内的整数不可变序列。
# 它是 bytearray 的不可变版本
a = bytes([1, 2, 18, ])
print(a, type(a))
# bytearray 回一个新字节数组。这个数组里的元素是可变的,
# 并且每个元素的值范围: 0 <= x < 256。
print(bytearray([1, 2, 21]))
print(bytearray('baidu', 'utf-8'))
# memoryview 返回元组列表
v = memoryview(bytearray("abcefg", 'utf-8'))
print(v[1])  # ASCII码
print(v[1:4])
print(v[1:4].tobytes())
b'\x01\x02\x12' <class 'bytes'>
bytearray(b'\x01\x02\x15')
bytearray(b'baidu')
98
<memory at 0x000002500479F048>
b'bce'
数据结构相关
序列--字符串
# chr() 返回整数参数对应的 ASCII 字符
print(chr(99))
print(chr(8361))
# ord() 字符串(Unicode 字符)作为参数,返回对应的 ASCII 数值
print(ord('a'))
print(ord('¥'))
 
数据结构相关
序列--字符串
# chr() 返回整数参数对应的 ASCII 字符
print(chr(99))
print(chr(8361))
# ord() 字符串(Unicode 字符)作为参数,返回对应的 ASCII 数值
print(ord('a'))
print(ord('¥'))
# repr() 函数将对象转化为供解释器读取的形式,
# 返回一个对象的 string 格式
dic1 = {'mryew': 'Mryew.com', 'baidu': 'baidu.com'}
ret1 = repr(dict)
print(ret1, type(repr(dict)))
# ascii() 返回字符串
a = ascii('Mryew')
print(a, type(a))
c

97
65509
<class 'dict'> <class 'str'>
'Mryew' <class 'str'>
数据结构相关
序列--slice()
reversed
# reversed 函数返回一个反转的迭代器
l1 = (1, 2, 23, 213, 2, 7)
print(l1)
print(list(reversed(l1)))
# 实现切片对象,主要用在切片操作函数里的参数传递
l2 = (1, 2, 23, 213, 5612, 342, 43)
sli = slice(1, 5, 2)
print(l2[sli])
(1, 2, 23, 213, 2, 7)
[7, 2, 213, 23, 2, 1]
(2, 213)
数据集合
—字典和集合
dict
# 传入键值对创建字典
dic1 = dict(a='a', b='b', t='t')
# 映射函数的方式构造字典
dic2 = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
# 可迭代对象方式构造字典
dic3 = dict([('one', 1), ('two', 2), ('three', 3)])
print(dic1, '\n', dic2, '\n', dic3, '\n',)
{'a': 'a', 'b': 'b', 't': 't'}
 {'one': 1, 'two': 2, 'three': 3}
 {'one': 1, 'two': 2, 'three': 3} 
数据集合
—字典和集合
set frozenset
# set 定义可变集合 frozenset定义非可变集合
set1 = set('hello')
fro_set1 = frozenset('hello')
print(set1, fro_set1)
 
数据集合# len()返回对象的长度或元素个数
s1 = 'Mryew'
li1 = [1, 'a6', '123', '狮']

print(len(s1), len(li1))
# enumerate() 将一个可遍历的对象组合为一个所索引
s2 = 'hello'
li2 = ['Spring', 'Summer', 'Fall', 'Winter']
print(list(enumerate(s2)))
print(list(enumerate(li2)))
# all 判断可迭代对象的元素中是否有空元素
#  0、空、None、False 都是空
a = ['a', 'b', 'None', 'd']
b = ['a', 'b', None, 'd']
c = ['a', 'b', False, 'd']
print(all(a), all(b), all(c))
# any 判断可迭代对象是否为空
# 只要有一个非空元素则为True
d = ['a', 'b', None, 'd']
e = [0, '', False, None]
print(any(d), any(e))
# zip 函数用于将可迭代的对象作为参数
f = [1, 2, 3]
h = [4, 5, 6]
z = zip(f, h)
print(z, list(z), type(z))
5 4
[(0, 'h'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
True False False
True False
<zip object at 0x0000019B77D98648>
[(1, 4), (2, 5), (3, 6)]
<class 'zip'>
数据集合
sorted
# sorted(*args,**kwargs)返回值:有序列表
l1 = [1, 3, 5, -2, -4, -6]
l2 = sorted(l1)
print(l2)
l3 = [[1, 2], [3, 4, 5, 6], (7,), '123']
print(sorted(l3, key=len))
print(sorted(l1, key=abs))
[-6, -4, -2, 1, 3, 5]
[(7,), [1, 2], '123', [3, 4, 5, 6]]
[1, -2, 3, -4, 5, -6]
数据集合
filter
# filter()函数接收一个函数 f 和一个list,
# 这个函数 f 的作用是对每个元素进行判断,返回 True或 False,
# filter()根据判断结果自动过滤掉不符合条件的元素,
# 返回由符合条件元素组成的新list。
def is_odd(x):
    return x % 2 == 1

li1 = filter(is_odd, [1, 4, 6, 7, 9, 12, 17])
print(li1, type(li1), list(li1))
# 用filter 删除空字符
def is_not_empty(s):
    return s and len(s.strip()) > 0
print(list(filter(is_not_empty, ['test', None, '', 'str', '  ', 'END'])))
# 用filter 获取 1~100 平方根是整数的
import math
def is_sqr(x):
    return math.sqrt(x) % 1 == 0
print(list(filter(is_sqr, range(1, 101))))
<filter object at 0x000001808A1E3400>
<class 'filter'> [1, 7, 9, 17]
['test', 'str', 'END']
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
数据集合
map
# map函数应用于每一个可迭代的项,返回的是一个结果list
# map()函数接收两个参数,一个是函数,一个是序列,
# map将传入的函数依次作用到序列的每个元素,
# 返回迭代器
def pow2(x):
    return x * x


li1 = [1, 2, 3, 4]
li2 = map(pow2,li1)
print(li2, type(li2), list(li2))
<map object at 0x00000211FE6FEBA8>
<class 'map'> [1, 4, 9, 16]
匿名函数
lambda
def calc(x):
    return x ** x

print(calc(10))

# 匿名函数
calc1 = lambda n: n ** n
print(calc1(10))
add = lambda x, y: x+y
print(add(3, 4))
10000000000
10000000000
7
匿名函数
lambda
res = map(lambda x: x**2, [1, 5, 7, 4, 8])
for i in res:
    print(i)
1
25
49
16
64
匿名函数
lambda
res = filter(lambda x: x > 10, [5, 8, 11, 9, 15])
for i in res:
    print(i)
11
15
匿名函数
lambda
l1 = [3, 2, 100, 999, 213, 1111, 31121, 333]
print(max(l1))

dic = {'k1': 10, 'k2': 100, 'k3': 30}

print(max(dic))
print(dic[max(dic, key=lambda k:dic[k])])
31121
k3
100

愿有更多的朋友,在网页笔记结构上分享更逻辑和易读的形式:

链接:暂无
提取码:暂无

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值