侧边栏壁纸
博主头像
张种恩的技术小栈博主等级

行动起来,活在当下

  • 累计撰写 747 篇文章
  • 累计创建 65 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

Python基础(16)之内置函数整理

zze
zze
2019-04-25 / 0 评论 / 0 点赞 / 696 阅读 / 15293 字

不定期更新相关视频,抖音点击左上角加号后扫一扫右方侧边栏二维码关注我~正在更新《Shell其实很简单》系列

数字相关

数据类型转换

bool()

转布尔类型。

print(bool([]))  # False
print(bool(''))  # False
print(bool(0))  # False
print(bool({}))  # False
print(bool(()))  # False

int()

转整形。

print(int('3'))  # 3

float()

转浮点型。

print(float('3'))  # 3.0

complex()

转复数类型。

print(complex('3'))  # (3+0j)

进制转换

bin()

转二进制。

print(bin(2))  # 0b10

oct()

转八进制。

print(oct(2))  # 0o2

hex()

转十六进制。

print(hex(2))  # 0x2

数学运算

abs()

绝对值。

print(abs(-3))  # 3

divmod()

除余。

print(divmod(9, 4))  # (2, 1)  商2余1

round()

精确小数位。

print(round(3.5687789,3))  # 3.569

pow()

幂运算。

print(pow(2,3))  # 8

sum()

求和。

print(sum([2,3]))  # 5

max()

最大值。

print(max([2,3]))  # 3

min()

最小值。

print(min([2,3]))  # 2

数据结构相关

类型转换

list()

转列表类型。

print(list((1,2,3)))  # [1, 2, 3]

tuple()

转元组类型。

print(tuple([1,2,3]))  # (1, 2, 3)

dict()

转字典类型。

print(dict({1:'a',2:'b'}))  # {1: 'a', 2: 'b'}

set()

转集合类型。

print(set([1,1,2,3,3]))  # {1, 2, 3}

frozenset()

转不可变集合类型。

only_read_set = frozenset([1, 1, 2, 3, 3]);
print(only_read_set)  # frozenset({1, 2, 3})
only_read_set[1] = 4  # TypeError: 'frozenset' object does not support item assignment

字符串相关

str()

转字符串。

print(str(123))  # 123

format()

将一个数值进行格式化显示。
如果参数 format_spec 未提供,则和调用 str() 效果相同。
对于不同的类型,参数 format_spec 可提供的值都不一样。

print(format(3.1415926))  # 3.1415926
# 字符串:指定对齐方式,<是左对齐, >是右对齐,^是居中对齐
print(format('format', '<20'))
print(format('format', '>20'))
print(format('format', '^20'))
# result:
# format
#               format
#        format

# 整形:
# 转换成二进制
print(format(3, 'b'))  # 11
# 转换unicode成字符
print(format(97, 'c'))  # a
# 转换成10进制
print(format(11, 'd'))  # 11
# 转换成8进制
print(format(11, 'o'))  # 13
# 转换成16进制 小写字母表示
print(format(11, 'x'))  # b
# 转换成16进制 大写字母表示
print(format(11, 'X'))  # B
# 和d一样
print(format(11, 'n'))  # 11
# 默认和d一样
print(format(11))  # 11

# 浮点型:
# 科学计数法,默认保留6位小数
print(format(314159267, 'e'))  # '3.141593e+08'
# 科学计数法,指定保留2位小数
print(format(314159267, '0.2e'))  # '3.14e+08'
# 科学计数法,指定保留2位小数,采用大写E表示
print(format(314159267, '0.2E'))  # '3.14E+08'
# 小数点计数法,默认保留6位小数
print(format(314159267, 'f'))  # '314159267.000000'
# 小数点计数法,默认保留6位小数
print(format(3.14159267000, 'f'))  # '3.141593'
##小数点计数法,指定保留8位小数
print(format(3.14159267000, '0.8f'))  # '3.14159267'
# 小数点计数法,指定保留10位小数
print(format(3.14159267000, '0.10f'))  # '3.1415926700'
# 小数点计数法,无穷大转换成大小字母
print(format(3.14e+1000000, 'F'))  # 'INF'

bytes()

转字节。

print(bytes('aaa', 'utf8'))  # b'aaa'
print('aaa'.encode('utf8'))  # b'aaa'

bytearray()

转字节数组。

print(bytearray('aaa', 'utf8'))  # bytearray(b'aaa')
for i in bytearray('aaa', 'utf8'):
    print(i)
    # 97
    # 97
    # 97

memoryview()

查看 bytes 内存地址。

print(memoryview(bytes('a', 'utf8')))  # <memory at 0x000000000272A588>

ord()

字符按 unicode 转数字。

print(ord('a'))  # 97

chr()

数字按 unicode 转字符。

print(chr(97))  # 'a'

ascii()

转 ascii 码。

# 只要是ascii码中的内容,就原样输出,不是就转换成\u格式
print(ascii('张三'))  # '\u5f20\u4e09'

repr()

将一个对象以字符串形式返回。

print('hello%r' % 'world')  # hello'world'
print(repr('1'))  # '1'
print(repr([1, 2, 3]))  # [1, 2, 3]

相关内置函数

len()

返回可迭代对象长度。

print(len([1, 1, 1]))  # 3
print(len('111'))  # 3
print(len({1: 'a', 2: 'b', 3: 'c'}))  # 3

enumerate()

枚举化。

print(list(enumerate(['a', 'b', 'c'])))  # [(0, 'a'), (1, 'b'), (2, 'c')]

all()

所有值都为 True 则返回 True,否则返回 False

print(all([True, '', 1]))  # False

any()

存在一个值为 True 则返回 True,否则返回 False

print(any([True, False, 0, '']))  # True

zip()

拉链方法,返回一个迭代器。

num_list = [1, 2, 3]
letter_list = ['a', 'b', 'c']
print(zip(num_list, letter_list))  # <zip object at 0x00000000021DB648>
print(list(zip(num_list, letter_list)))  # [(1, 'a'), (2, 'b'), (3, 'c')]

filter()

过滤。

# 筛选num_list里的奇数
num_list = [1, 2, 3, 4, 5, 6]
result_list = filter(lambda i: i % 2 == 1, num_list)
print(list(result_list))  # [1, 3, 5]
# 等价于
print(list(i for i in num_list if i % 2 == 1))  # [1, 3, 5]

map()

映射。

# 取列表中每个数的平方
num_list = [1, 2, 3, 4, 5, 6]
print(list(map(lambda i: i ** 2, num_list)))  # [1, 4, 9, 16, 25, 36]

sorted()

排序。

num_list = [-1, -2, 3, -4]
# 默认排序
print(sorted(num_list))  # [-4, -2, -1, 3]
# 以列表中数字的绝对值升序
print(sorted(num_list, key=abs))  # [-1, -2, 3, -4]
# 以列表中数字的绝对值降序
print(sorted(num_list, key=abs, reverse=True))  # [-4, 3, -2, -1]

面向对象相关

定义特殊方法的装饰器

@classmethod

定义类方法。

class A:
    @classmethod
    def print(self):
        print('from A')


A.print()  # from A

@staticmethod

定义静态方法。

class A:
    @staticmethod
    def print():
        print('from A')


A.print()  # from A

@property

将方法包装成属性。

class Person:
    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, new_name):
        self.__name = new_name

    @name.deleter
    def name(self):
        print('执行删除name操作')


p = Person('张三', 18)
print(p.name)  # 张三
p.name = '李四'
print(p.name)  # 李四
# 只是触发对应deleter装饰的函数,具体操作需在函数类完成
del p.name  # 执行删除name操作
print(p.name)  # 李四

判断对象/类与类之间的关系

isinstance()

判断一个对象是不是指定类的实例。

class A: pass

class B: pass

a = A()
print(isinstance(a, A))  # True

print(isinstance(a, B))  # False

issubclass()

判断一个类指定类的子类。

class A: pass

class B(A): pass

class C: pass

print(issubclass(B, A))  # True
print(issubclass(B, C))  # False

object()

所有类的基类。

class A: pass

class B(A): pass

class C: pass

print(issubclass(A, object))  # True
print(issubclass(B, object))  # True
print(issubclass(C, object))  # True

super()

获取父类。

class A:
    @classmethod
    def func(self):
        print('print in A')

class B(A):
    @classmethod
    def func(self):
        super().func()
        super(B, self).func()
        print('print in B')

B.func()

# result:
# print in A
# print in A
# print in B

其它

作用域相关

locals()

将当前函数块的所有变量以字典类型返回。

a = 1
def outer():
    a = 2
    def inner():
        b = 3
        print(locals())
    inner()
    
outer()
# result
# {'b': 3}

globals()

将全局变量以字典类型返回。

a = 1
def outer():
    a = 2
    def inner():
        b = 3
        print(globals())
    inner()

outer()
# result
# {'__name__': '__main__', '__doc__': None, '__package__': None, ..., 'a': 1, 'outer': <function outer at 0x000000000203C268>}

迭代器/生成器相关

range()

返回指定区间数字生成器。

for i in range(1, 4):
    print(i)
# result:
# 1
# 2
# 3

iter()

传入可迭代对象返回迭代器。

print(iter(range(1, 4)))  # <range_iterator object at 0x0000000002792470>

next()

迭代器取下一个值。

range_iter = iter(range(1, 3))
print(range_iter.__next__())  # 1
print(range_iter.__next__())  # 2
print(range_iter.__next__())  # StopIteration 取不到值抛异常

字符串类型代码的执行

eval()

执行且有返回值。

print(eval('1+1'))  # 2

exec()

执行无返回值。

print(exec('1+1'))  # None

compile()

返回字符串编译后字节代码对象。

str = "for i in range(0,10): print(i)"
c = compile(str, '', 'exec')  # 编译为字节代码对象
exec(c)
# result:
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
str = "3 * 4 + 5"
a = compile(str, '', 'eval')
print(eval(a))  # 17

反射相关

hasattr()

判断指定类或实例是否拥有指定属性。

class Person:
    gender = '男'

    def __init__(self, name, age):
        self.name = name
        self.age = age


# 判断Person的实例p是否拥有name属性
p = Person('张三', '李四')
print(hasattr(p, 'name'))  # True
# 判断Person类是否拥有name属性
print(hasattr(Person, 'name'))  # False
# 判断Person类是否拥有gender属性
print(hasattr(Person, 'gender'))  # True

getattr()

获取指定类或实例的指定属性引用。

class Person:
    gender = '男'

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def show_name(self):
        print(self.name)


p = Person('张三', 18)
# 获取实例的属性
print(getattr(p, 'age'))
# 获取实例的方法
getattr(p, 'show_name')()

setattr()

给指定类或对象的属性赋值,没有则创建后再赋值。

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def show_name(self):
        print(self.name)


print(hasattr(Person, 'gender'))  # False  默认没有gender属性
setattr(Person, 'gender', '男')
print(hasattr(Person, 'gender'))  # True

delattr()

删除指定类或对象的指定属性。

class Person:
    gender = '男'

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def show_name(self):
        print(self.name)


print(hasattr(Person, 'gender'))  # True
delattr(Person, 'gender')
print(hasattr(Person, 'gender'))  # False

输入输出

input()

以字符串类型返回输入值。

>>> input('input your name:')
input your name:zhangsan
'zhangsan'

print()

输出。

>>> print('hello world')
hello world

内存相关

hash()

返回对象在内存中的哈希标识。

print(hash('a'))  # -1985915095439783199

id()

返回对象在内存中的地址标识。

print(id('a'))  # 34187784

文件操作相关

open()

具体见【文件操作】。

模块相关

import()

模块导入。

time =__import__('time')# 等价于 import time
print(time.time())

调用相关

callable()

判断对象是否可调用,返回 TrueFalse

def func():
    return 1 + 1

a = 1
print(callable(a))  # False
a = func
print(callable(a))  # True

查看信息

help()

返回类型的帮助信息。

print(help(str))

# class str(object)
#  |  str(object='') -> str
#  |  str(bytes_or_buffer[, encoding[, errors]]) -> str
#  |
#  |  Create a new string object from the given object. If encoding or
#  |  errors is specified, then the object must expose a data buffer
#  |  that will be decoded using the given encoding and error handler.
#  |  Otherwise, returns the result of object.__str__() (if defined)
#  |  or repr(object).
#  |  encoding defaults to sys.getdefaultencoding().
#  |  errors defaults to 'strict'.
#  |
#  |  Methods defined here:
...

dir()

以字符串列表返回对象类型的属性及函数。

print(dir('a'))  
# ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
0

评论区