Python内置函数 built-in

内置函数 built-in

1. 数字相关

1. 进制转换

  • bin():转化成二进制
print(bin(2))   # 0b10
  • oct():转化为八进制
print(oct(22))   # 0o26
  • hex():转化为十六进制
print(hex(22))   # 0x16

2. 数据类型

  • bool:布尔类型(True, False)
  • int:整型
  • float:浮点型
  • complex:复数

3. 数学运算

  • abs() :返回绝对值
print(ads(-22))   # 22
  • divmod(): 返回商和余数
print(divmod(22, 3))   # (7, 1)
  • round() :四舍五入
print(round(32.2345, 2))   # 32.23
  • pow(a, b,z=none) :求a的b次幂, 如果有三个参数. 则求完次幂后对第三个数取余
print(pow(2, 3))  # 8
print(pow(2, 3, 3))  # 2
  • sum() :求和
print(sum([1, 2, 3, 5]))    # 11
  • min() :求最小值
print(min([1, 2, 3, 5]))    # 1
  • max() :求最大值
print(max([1, 2, 3, 5]))    # 5
  • eval() :执行字符串类型的代码. 并返回最终结果
s = input("请输入a+b:")   # 输入:2+3
print(eval(s)) 		 # 5 可以动态的执行代码

2. 数据结构相关

1. 序列

  • list() :将一个可迭代对象转换成列表
print(list((1, 2, 3)))   # [1, 2, 3]
  • tuple() :将一个可迭代对象转换成元组
print(tuple([1, 2, 3]))  # (1, 2, 3)
  • reversed() :将一个序列翻转, 返回翻转序列的迭代器
list1 = [2, 3, 4, 6]
list2 = list(reversed(list1))
print(list2)	# [6, 4, 3, 2]
  • **slice() **:列表的切片
list1 = [2, 3, 4, 6]
s = slice(1, 3, 1)
print(list1[s])		# [3, 4]

2. 数据

  • **str() **:将数据转化成字符串
print(type(str(22)))	# <class 'str'>
  • format():与具体数据相关, 用于计算各种小数, 精算等.
str1 = "hello world!"
print(format(str1, "^20"))  # 居中		 #     hello world!    
print(format(str1, "<20"))  # 左对齐		# hello world!        
print(format(str1, ">20"))  # 右对齐 		#         hello world!

# 进制
print(format(2, 'b' ))    # 二进制:10
print(format(98, 'c' ))   # 转换成unicode字符:b
print(format(22, 'd' ))   # ⼗进制:22
print(format(22, 'o' ))   # 八进制:26
print(format(10, 'x' ))   # 十六进制(⼩写字母):a
print(format(10, 'X' ))   # 十六进制(大写字母):A
print(format(22, 'n' ))   # 和d⼀样:22
print(format(22))         # 和d⼀样:22

# 科学计算
print(format(123456789, 'e' ))      # 科学计数法. 默认保留6位小数:1.234568e+08
print(format(123456789, '0.2e' ))   # 科学计数法. 保留2位小数(小写):1.23e+08
print(format(123456789, '0.2E' ))   # 科学计数法. 保留2位小数(大写):1.23E+08
print(format(1.23456789, 'f' ))     # 小数点计数法. 保留6位小数:1.234568
print(format(1.23456789, '0.2f' ))  # 小数点计数法. 保留2位小数:1.23
print(format(1.23456789, '0.10f'))  # 小数点计数法. 保留10位小数:1.2345678900
print(format(1.23456789e+3, 'F'))   # 小数点计数法. 很大的时候输出INF:1234.567890
  • bytes() :把字符串转化成bytes类型
bs = bytes("学习python", encoding="utf-8")
print(bs)  # b'\xe5\xad\xa6\xe4\xb9\xa0python'
  • bytearray():返回一个新字节数组. 这个数字的元素是可变的, 并且每个元素的值得范围是[0, 256]
byt = bytearray("nancy" ,encoding="utf-8")
print(ret)  	# bytearray(b'nancy')
print(ret[1])	# 97
byt[1] = 98		# 把byt[1]的位置赋值为字符编码98位置的值
print(byt)		# bytearray(b'nbncy')
  • ord():输入字符获得对应的字符编码的位置
print(ord('b'))     # 98
  • chr() :输入位置数字获得对应的字符
print(chr(98))		# b
  • ascii() :是ascii码中的返回该值 不是就返回u
print(ascii('hello'))		# hello
  • repr() :返回一个对象的string形式
str1 = "今天\t加了%s小时\n班" % 3
print(str1)
# 今天	加了3小时
# 班
print(repr(str1))		# repr()输出原样的字符串,过滤掉转义字符 \n \t \r 但是不过滤百分号%
# '今天\t加了3小时\n班'

3. 数据集合

  • dict: 创建一个字典
  • set: 创建一个集合
    • frozenset() 创建一个冻结的集合,冻结的集合不能进行添加和删除操作。
s1 = set([1, 2, 3, 4])
print(s1)					# {1, 2, 3, 4}
s1.add(5)				
print(s1)					# {1, 2, 3, 4, 5}
s2 = frozenset([1, 2, 3])
print(s2)					# frozenset({1, 2, 3})
s2.add(4)
print(s2)					# AttributeError: 'frozenset' object has no attribute 'add'
  • len() :返回一个对象中的元素的个数
print(len([1, 2, 3, 4]))     # 4
  • sorted() :对可迭代对象进行排序操作
    • sorted**(iterable, key=itemgetter, reverse=bool)**
      • iterable:可迭代对象
      • key**=**itemgetter:排序规则
      • reverse**=**bool:是否倒序,True为倒序,False为正序,默认为正序
list1 = [2, 1, 45, 3, 1, 0, -4, 20, 33]
list2 = sorted(list1)
print(list2)  		# [-4, 0, 1, 1, 2, 3, 20, 33, 45]
list3 = sorted(list1,reverse=True) 
print(list3) 		# [45, 33, 20, 3, 2, 1, 1, 0, -4]

# 根据字符串长度给列表排序
list4 = ['aa', 'b', 'adbc', 'ff', 'hello world']
def func(s):
    return len(s)
list5 = sorted(list4, key=func)
print(list5)		# ['b', 'aa', 'ff', 'adbc', 'hello world']
  • enumerate() :获取集合的枚举对象
list6 = ['aa', 'b', 'adbc', 'ff', 'hello world']
for index, i in enumerate(list6):
    print(index, i)
# 0 aa
# 1 b
# 2 adbc
# 3 ff
# 4 hello world
  • **all() **:可迭代对象中全部是True, 结果才是True
print(all([1, 'he', 'll', 'o']))		# True
print(all([1, 'he', 'll', 'o', 1>2]))	# False
  • any() :可迭代对象中有一个是True, 结果就是True
print(any([False, 0, 0, 1>2, 2]))		# True
  • zip(): 函数用于将可迭代的对象作为参数, 将对象中对应的元素打包成一个元组, 然后返回由这些元组组成的列表. 如果各个迭代器的元素个数不一致, 则返回列表长度与最短的对象相同
list7 = [1, 2, 3, 4]
list8 = ['a', 'b', 'c', 'd']
list9 = ['hello', 'world']
for i in zip(list7, list8, list9):
    print(i)
# (1, 'a', 'hello')
# (2, 'b', 'world')
  • fiter(function. Iterable): 用来筛选的函数. 在filter中会自动的把iterable中的元素传递给function. 然后根据function返回的True或者False来判断是否保留留此项数据 , Iterable: 可迭代对象
list10 = ['aa.log', 'bb.log', 'cc']
print(filter(lambda x: x.endswith('.log'), list10))
print(list(filter(lambda x: x.endswith('.log'), list10)))
# <filter object at 0x7fc87628afd0>
# ['aa.log', 'bb.log']
  • **map(function, iterable) **:可以对可迭代对象中的每一个元素进行映射. 分别去执行 function
list11 = [1, 2, 3]
def func(i):
    return i + 10
print(map(func, list11))
print(list(map(func, list11)))
# <map object at 0x7f9bf4184550>
# [11, 12, 13]

3. 作用域相关

  • **locals() **:返回当前作用域中的名字
  • **globals() **:返回全局作用域中的名字
str1 = 'roy'
def func():
    my_syr = 'nancy'
    print(locals())
    print(globals())
func()
# {'my_syr': 'nancy'}
"""
{'__name__': '__main__', '__doc__': None, '__package__': None, 
'__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fc502071fd0>, 
'__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 
'__file__': '/Users/roy/Documents/my_code/test_a/built-in.py', '__cached__': None, 
'str1': 'roy', 'func': <function func at 0x7fc5020ea680>}
"""

4. 输入输出

  • print():打印
  • input():输入

5. 帮助

  • help():查看函数或模块用途的详细说明
print(help(input))
"""
Help on built-in function input in module builtins:

input(prompt=None, /)
    Read a string from standard input.  The trailing newline is stripped.
    
    The prompt string, if given, is printed to standard output without a
    trailing newline before reading input.
    
    If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
    On *nix systems, readline is used if available.

None
"""

6. 迭代器&生成器

  • range() : 生成数据
  • **next() : **迭代器向下执行一次, 内部实际使⽤用了__ next__()⽅方法返回迭代器的下一个项目
  • iter() : 获取迭代器, 内部实际使用的是__ iter__()⽅方法来获取迭代器
for i in range(1, 4):
    print(i)
# 1
# 2
# 3
list11 = [2, 4, 6, 8, 10]
iter1 = iter(list11)
print(iter1.__next__())		# 2
print(next(iter1))			# 4
print(next(iter1))			# 6
print(next(iter1))			# 8

7. 内存相关

  • hash() : 获取到对象的哈希值(int, str, bool, tuple)
    • hash算法
      • 目的是唯一性
      • dict 查找效率非常高, 因为dict的key以hash值作为索引存储。hash表用空间换的时间,比较耗费内存
print(hash('nancy'))		# 1290694029433281375

8. 文件操作相关

  • open() : 用于打开一个文件, 创建一个文件句柄
f = open('test_file', mode='r', encoding='utf-8')
print(f)			# <_io.TextIOWrapper name='test_file' mode='r' encoding='utf-8'>
print(f.read())		# test word
f.close()		# open()方法打开文件,最后要用close()关闭,否则占用内存
  • **with open(path, mode, encoding) as f:**也是打开文件,不用手动关闭,程序结束后自动释放资源

9. 调用相关

  • callable() : 用于检查一个对象是否是可调用的. 如果返回True, object有可能调用失败, 但如果返回False. 那调用绝对不会成功
t = 'nancy'
print(callable(t))			# False

def func():
    print("hello nancy")	# hello nancy
    print(callable(func))   # True
func()

10. 查看内置属性

  • dir() : 查看对象的内置属性, 访问的是对象中的__dir__()方法,返回值为
print(dir(list))
"""
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', 
'__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', 
'__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', 
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', 
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', 
'__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 
'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
"""

汇总

# 内置函数

abs()  all()  any()  ascii()  
bin()  bool()  bytearray()  bytes()  
callable()  chr()  classmethod()  compile()  complex()  
dict()  dir()  delattr()  divmod()  
enumerate()  eval()  exec()    
format()  frozenset()  filter()  float()
globals()  getattr()
hasattr()  hash()  help()  hex()  
id()  input()  int()  issubclass()  iter()  isinstance() 
len()  list()  locals()  
map()  max()  memoryview()  min()  
next()  
object()  oct()  open()  ord()  
pow()  print()  property()
range()  repr()  reversed()  round()  
set()  setattr()  slice()  staticmethod()  str()  sum()  super()  sorted()
type()  tuple()  
vars()  
zip()
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值