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
相关文章
|
16天前
|
存储 人工智能 数据处理
Python:编程的艺术与科学的完美交融
Python:编程的艺术与科学的完美交融
19 1
|
3天前
|
JSON 数据格式 开发者
pip和requests在Python编程中各自扮演着不同的角色
`pip`是Python的包管理器,用于安装、升级和管理PyPI上的包;`requests`是一个HTTP库,简化了HTTP通信,支持各种HTTP请求类型及数据交互。两者在Python环境中分别负责包管理和网络请求。
15 5
|
5天前
|
存储 Python 容器
Python高级编程
Python集合包括可变的set和不可变的frozenset,用于存储无序、不重复的哈希元素。创建集合可使用{}或set(),如`my_set = {1, 2, 3, 4, 5}`。通过add()添加元素,remove()或discard()删除元素,如`my_set.remove(3)`。
|
6天前
|
测试技术 Python
Python模块化方式编程实践
Python模块化编程提升代码质量,包括:定义专注单一任务的模块;使用`import`导入模块;封装函数和类,明确命名便于重用;避免全局变量降低耦合;使用文档字符串增强可读性;为每个模块写单元测试确保正确性;重用模块作为库;定期维护更新以适应Python新版本。遵循这些实践,可提高代码可读性、重用性和可维护性。
27 2
|
12天前
|
测试技术 调度 索引
python编程中常见的问题
【4月更文挑战第23天】
32 2
|
12天前
|
网络协议 算法 网络架构
Python网络编程之udp编程、黏包以及解决方案、tcpserver
Python网络编程之udp编程、黏包以及解决方案、tcpserver
|
13天前
|
编解码 JavaScript 前端开发
【专栏】介绍了字符串Base64编解码的基本原理和在Java、Python、C++、JavaScript及Go等编程语言中的实现示例
【4月更文挑战第29天】本文介绍了字符串Base64编解码的基本原理和在Java、Python、C++、JavaScript及Go等编程语言中的实现示例。Base64编码将24位二进制数据转换为32位可打印字符,用“=”作填充。文中展示了各语言的编码解码代码,帮助开发者理解并应用于实际项目。
|
13天前
|
机器学习/深度学习 数据挖掘 算法框架/工具
Python:编程的艺术与魅力
Python:编程的艺术与魅力
25 3
|
13天前
|
机器学习/深度学习 数据可视化 数据挖掘
实用技巧:提高 Python 编程效率的五个方法
本文介绍了五个提高 Python 编程效率的实用技巧,包括使用虚拟环境管理依赖、掌握列表推导式、使用生成器提升性能、利用装饰器简化代码结构以及使用 Jupyter Notebook 进行交互式开发。通过掌握这些技巧,可以让你的 Python 编程更加高效。
|
13天前
|
算法 Python
Python面向对象oop编程(二)
Python面向对象oop编程(二)