Python编程:Built-in Functions内建函数小结

简介: Python编程:Built-in Functions内建函数小结

Built-in Functions(68个)

1、数学方法

abs() sum() pow() min() max() divmod() round()


2、进制转换

bin() oct() hex()


3、简单数据类型

- 整数:int()

- 浮点数:float()

- 字符\字符串:str() repr() ascii() ord() chr() format()

- 字节:bytes() bytearray()

- 布尔:bool()

- 复数:complex()


4、数据结构

- 列表:list() slice() range()

- 元组:tuple()

- 字典:dict() hash()

- 集合:set() frozenset()

- 方法:len() zip() all() any() iter() filter() next() sorted() reversed() enumerate() map() memoryview()


5、面向对象

setattr() getattr() delattr() hasattr()

super() property()

staticmethod() classmethod()

isinstance() issubclass()


6、系统方法

dir() help() id() object() type()

input() open() print()

eval() exec() compile()

vars() locals() globals()

callable() __import__()


参考:https://docs.python.org/3.5/library/functions.html


print(abs(-1))  # 绝对值  1
print(divmod(5, 2))  # 取商和余数 (2, 1)
# 四舍五入
print(round(1.4)) # 1
print(round(1.5)) # 2
print(round(1.6)) # 2
# 次方,相当于x**y
print(pow(2, 8))  # 256
print(bin(2))  # 转为二进制  0b10
print(oct(12))  # 转8进制 0o14
print(hex(20))  # 转16进制  0x14
print(bool(1))  # 转为布尔值  True
# 转为int
s = "12"
i = int(s)
print(type(s), type(i))  # <class 'str'> <class 'int'>
# 转字符串
i = 12345
s =str(i)
print(type(i), type(s))   # <class 'int'> <class 'str'>
print([ascii([1,2,3])])  # 转为字符串  ['[1, 2, 3]']
# 转为可打印对象representation 表现
s = 123456
r =repr(s)
print(type(s), type(r))  # <class 'int'> <class 'str'>
# ascii码
print(chr(100))  # d
print(ord("a"))  # 97
print(bytes("我是中国人", encoding="utf-8"))
# b'\xe6\x88\x91\xe6\x98\xaf\xe4\xb8\xad\xe5\x9b\xbd\xe4\xba\xba'
b = bytearray("abc", encoding="utf-8")  # 转为字节数组
print(b)  # bytearray(b'abc')
print(b[0])  # 97
b[0] = 100
print(b)  # bytearray(b'dbc')
# 新建字典对象
d1 = {}
d2 = dict()
d3 = dict(name = "Tom", age = 23)
print(d1)  # {}
print(d2)  # {}
print(d3)  # {'age': 23, 'name': 'Tom'}
# 获取散列值
res = hash(1)
print(res)  # 1
res = hash("Tom")  # -1433634475463391166
print(res)
# 不可变集合
st = frozenset([1,2,3,4])
print(type(st))  # <class 'frozenset'>
# 生成列表
lst1 = []
lst2 = list()
lst3 = list((1,2,3))
print(lst1)  # []
print(lst2)  # []
print(lst3)  # [1, 2, 3]
# 计算长度
print(len([1,2,3]))  # 3
# 最大最小值
lst = [1,3,4,5,8,6,9]
print(max(lst))  # 9
print(min(lst))  # 1
# 求和
lst = [i for i in range(5)]
print(sum(lst))  # 10
# 切片
lst = [x for x in range(10)]
s = slice(2,5)
print(lst[s])  # [2, 3, 4]
# 枚举
for index, value in enumerate(range(1,5)):
    print(index, value)
"""
0 1
1 2
2 3
3 4
"""
print(all([1,2,3]))  # 所有都是真的  True
print(all([1,2,0]))  # False
print(any([1,2,1]))  # 至少存在一个真的  True
print(any([0]))  # False
# 元组
t1 = ()
t2 = (1,)
t3 = tuple()
print(type(t1))  # <class 'tuple'>
print(type(t2))  # <class 'tuple'>
print(type(t3))  # <class 'tuple'>
# 反转
lst = [1, 2, 3]
print(reversed(lst))  # <list_reverseiterator object at 0x0000000003A54A90>
# lambda 与 三元运算符
lamb = lambda x : 3 if x < 5 else x
print(lamb(5))  # 5
# 过滤
res = filter(lambda x: x>5, range(10))
for i in res:
    print(i,end=" ")  # 6 7 8 9
print()
# 映射
res = map(lambda x: x*x, range(10))
for i in res:
    print(i, end=" ")  # 0 1 4 9 16 25 36 49 64 81
print()
"""
等价于:
res = [lambda x: x*x for x in range(10)]
res = [x*x for x in range(10)]
"""
# 浓缩
import functools  # py3
res = functools.reduce(lambda x, y: x + y, range(10))
print(res)  # 45
# 排序
dct ={"0": 99, "1": 98, "6": 11, "5": 45}
print(dct)  # {'6': 11, '0': 99, '1': 98, '5': 45}
print(sorted(dct))  # ['0', '1', '5', '6']
print(sorted(dct.items()))
# [('0', 99), ('1', 98), ('5', 45), ('6', 11)]
print(sorted(dct.items(), key=lambda x: x[1]))
# [('6', 11), ('5', 45), ('1', 98), ('0', 99)]
# 拉链,这个叫法很形象
a = [1, 2, 3, 4, 5]
b = ["a", "b", "c", "d", "e"]
z = zip(a, b)
print(z)  # <zip object at 0x0000000003FBE1C8>
print([i for i in z])
# [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
# 转为迭代器
lst = [1, 2, 3]
ilst = iter(lst)
print(type(lst),type(ilst))  # <class 'list'> <class 'list_iterator'>
# 相当于生成器的__next()__ 方法
lst = range(5)
print(type(ilst))  # <class 'range'>
ilst = iter(lst)
print(type(ilst))  # <class 'range_iterator'>
print(next(ilst))  # 0
print(next(ilst))  # 1
# 判断是否为某个类的实例
d ={}
print(isinstance(d, dict))  # True
# 导入包  动态加载类和函数
__import__("iterator_test")
print()
print(dir(d1))  # 查看方法
"""
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__',
 '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', 
 '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__',
 '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
 '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', 
 '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 
 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
"""
print(help(divmod))  # 查看帮助
"""
Help on built-in function divmod in module builtins:
divmod(...)
    divmod(x, y) -> (div, mod)
    Return the tuple ((x-x%y)/y, x%y).  Invariant: div*y + mod == x.
"""
# 对象id
a = 1
print(id(a))  # 1430299072
# 打印局部变量
def foo():
    a = 1
    print(vars())  # {'a': 1}
foo()
# 打印局部变量
def foo():
    a = 1
    print(locals())  # {'a': 1}
foo()
print(globals())  # 打印当前文件的所有全局变量,key-value形式返回
"""
{'code': '\nfor i in range(5):\n    print(i, end=" ")\n',
 '__cached__': None, 'value': 4, 'index': 3, 'd1': {}, 
 'b': bytearray(b'dbc'), 'lamb': <function <lambda> at 0x00000000024E8730>, 
 '__package__': None, 'st': frozenset({1, 2, 3, 4}),
 ...
"""
code = """
for i in range(5):
    print(i, end=" ")
"""
exec(code)  # 运行代码  0 1 2 3 4
x = 1
print("eval:", eval("x+1"))  # eval: 2
def sayHello():pass
print(callable(sayHello))  # True
相关文章
|
1天前
|
Python
【Python操作基础】——函数
【Python操作基础】——函数
|
1天前
|
Python
Python的全局变量作用于整个程序,生命周期与程序相同,而局部变量仅限函数内部使用,随函数执行结束而销毁。
Python的全局变量作用于整个程序,生命周期与程序相同,而局部变量仅限函数内部使用,随函数执行结束而销毁。在函数内部修改全局变量需用`global`关键字声明,否则会创建新局部变量。
9 2
|
3天前
|
JSON 数据格式 开发者
pip和requests在Python编程中各自扮演着不同的角色
`pip`是Python的包管理器,用于安装、升级和管理PyPI上的包;`requests`是一个HTTP库,简化了HTTP通信,支持各种HTTP请求类型及数据交互。两者在Python环境中分别负责包管理和网络请求。
16 5
|
4天前
|
Java C# 开发者
Python 中的类型注解是一种用于描述变量、函数参数和返回值预期类型的机制
Python的类型注解提升代码可读性和可维护性,虽非强制,但利于静态类型检查(如Mypy)。包括:变量注解、函数参数和返回值注解,使用内置或`typing`模块的复杂类型,自定义类型注解,以及泛型模拟。类型注解可在变量声明、函数定义和注释中使用,帮助避免类型错误,提高开发效率。
16 6
|
6天前
|
存储 Python
【Python 基础】解释reduce函数的工作原理
【5月更文挑战第6天】【Python 基础】解释reduce函数的工作原理
|
6天前
|
Python
【Python 基础】解释map函数的工作原理
【5月更文挑战第6天】【Python 基础】解释map函数的工作原理
|
6天前
|
索引 Python
【Python 基础】解释Range函数
【5月更文挑战第6天】【Python 基础】解释Range函数
|
6天前
|
存储 Python 容器
Python高级编程
Python集合包括可变的set和不可变的frozenset,用于存储无序、不重复的哈希元素。创建集合可使用{}或set(),如`my_set = {1, 2, 3, 4, 5}`。通过add()添加元素,remove()或discard()删除元素,如`my_set.remove(3)`。
|
6天前
|
Python
Python中的匿名函数,即lambda函数
【5月更文挑战第6天】Python中的匿名函数,即lambda函数,用于简洁地定义小型函数,无需`def`关键字。示例:`double = lambda x: x * 2`,可将5加倍。常用于排序(自定义比较)、映射(如求平方)和过滤列表,以及作回调函数。然而,它们不适用于多行代码或复杂逻辑,此时需用常规函数。
4 0
|
7天前
|
测试技术 Python
Python模块化方式编程实践
Python模块化编程提升代码质量,包括:定义专注单一任务的模块;使用`import`导入模块;封装函数和类,明确命名便于重用;避免全局变量降低耦合;使用文档字符串增强可读性;为每个模块写单元测试确保正确性;重用模块作为库;定期维护更新以适应Python新版本。遵循这些实践,可提高代码可读性、重用性和可维护性。
28 2