​学了快一年的 Python 了,突然发现,内置函数能够大大的加快开发时的效率,花了一周时间整理了一下 68 个内置函数,来看看内置函数的骚操作吧!

由于平台原因图片不是很清晰如果想要获取高清的照片或者 pdf,可以去 github 上我的仓库获取或者扫一个照片获得。 有公众号的回复:003

github 地址:https://github.com/hellgoddess/PythonGuide

我们先从简单的开始,再次向大家推荐一下 python 各种各样的内置函数,是真的好用,用起来不用自己手写函数,真的是太爽了,我直呼好家伙。

数学运算

>>> abs(-2)
2
>>> divmod(9,4)
(21)
>>> divmod(3.3,2)
(1.01.2999999999999998)
>>> max(1,2,3)
3
>>> max('123456')
'6'
>>> max(-1,0)
0
>>> max(-1,0,key=abs) # 传入了绝对值函数,则所有的参数都会进行绝对值求和再取最大值
-1

例子 max,只是到了过来

>>> pow(2,3)
8
>>> 2**3
8
>>> pow(2,3,5)
3
>>> pow(2,3)%5
3
>>> round(1.31491)
1.3
>>> round(1.13952456,3)
1.14
>>> sum((1,2,3,4))
10

类型转换:类型转换中,我来介绍几个我们常用的

>>> tuple() #不传入参数,创建空元组
()
>>> tuple('121'#传入可迭代对象。使用其元素创建新的元组
('1''2''1')
>>>list() # 不传入参数,创建空列表
[] 
>>> list('abcd'# 传入可迭代对象,使用其元素创建新的列表
['a''b''c''d']
>>> dict() # 不传入任何参数时,返回空字典。
{}
>>> dict(a = 1,b = 2#  可以传入键值对创建字典。
{'b'2'a'1}
>>> dict(zip(['a','b'],[1,2])) # 可以传入映射函数创建字典。
{'b'2'a'1}
>>> dict((('a',1),('b',2))) # 可以传入可迭代对象创建字典。
{'b'2'a'1}
>>>set() # 不传入参数,创建空集合
set()
>>> a = set(range(10)) # 传入可迭代对象,创建集合
>>> a
{0123456789}
>>> a = frozenset(range(10))
>>> a
frozenset({0123456789})
>>> seasons = ['Spring''Summer''Fall''Winter']
>>> list(enumerate(seasons))
[(0'Spring'), (1'Summer'), (2'Fall'), (3'Winter')]
>>> list(enumerate(seasons, start=1)) #指定起始值
[(1'Spring'), (2'Summer'), (3'Fall'), (4'Winter')]
>>> a = range(10)
>>> b = range(1,10)
>>> c = range(1,10,3)
>>> a,b,c # 分别输出a,b,c
(range(010), range(110), range(1103))
>>> list(a),list(b),list(c) # 分别输出a,b,c的元素
([0123456789], [123456789], [147])

>>> a = iter('abcd'#字符串序列
>>> a
<str_iterator object at 0x03FB4FB0>
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#29>", line 1in <module>
    next(a)
StopIteration

序列操作

>>> all([1,2]) #列表中每个元素逻辑值均为True,返回True
True
>>> all([0,1,2]) #列表中0的逻辑值为False,返回False
False
>>> all(()) #空元组
True
>>> all({}) #空字典
True
>>> any([0,1,2]) #列表元素有一个为True,则返回True
True
>>> any([0,0]) #列表元素全部为False,则返回False
False
>>> any([]) #空列表
False
>>> any({}) #空字典
False
>>> a = list(range(1,10)) #定义序列
>>> a
[123456789]
>>> def if_odd(x): #定义奇数判断函数
    return x%2==1

>>> list(filter(if_odd,a)) #筛选序列中的奇数
[13579]
>>> a = map(ord,'abcd')
>>> a
<map object at 0x03994E50>
>>> list(a)
[979899100]
>>> a = iter('abcd')
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#18>", line 1in <module>
    next(a)
StopIteration

#传入default参数后,如果可迭代对象还有元素没有返回,则依次返回其元素值,如果所有元素已经返回,则返回default指定的默认值而不抛出StopIteration 异常
>>> next(a,'e')
'e'
>>> next(a,'e')
'e'
>>> a = reversed(range(10)) # 传入range对象
>>> # 类型变成迭代器
<range_iterator object at 0x035634E8>
>>> list(a)
[9876543210]
>>> a = ['a','b','d','c','B','A']
>>> a
['a''b''d''c''B''A']

>>> sorted(a) # 默认按字符ascii码排序
['A''B''a''b''c''d']

>>> sorted(a,key = str.lower) # 转换成小写后再排序,'a'和'A'值一样,'b'和'B'值一样
['a''A''b''B''c''d']
>>> x = [1,2,3#长度3
>>> y = [4,5,6,7,8#长度5
>>> list(zip(x,y)) # 取最小长度3
[(14), (25), (36)]

对象操作(用的少,可在思维导图中找到用法解说)

反射操作

index = __import__('index')
index.sayHello()
>>> isinstance(1,int)
True
>>> isinstance(1,str)
False
>>> isinstance(1,(int,str))
True
>>> issubclass(bool,int)
True
>>> issubclass(bool,str)
False

>>> issubclass(bool,(str,int))
True
#定义类A
>>> class Student:
    def __init__(self,name):
        self.name = name

        
>>> s = Student('Aim')
>>> hasattr(s,'name'#a含有name属性
True
>>> hasattr(s,'age'#a不含有age属性
False
#定义类Student
>>> class Student:
    def __init__(self,name):
        self.name = name

>>> getattr(s,'name'#存在属性name
'Aim'

>>> getattr(s,'age',6#不存在属性age,但提供了默认值,返回默认值

>>> getattr(s,'age'#不存在属性age,未提供默认值,调用报错
Traceback (most recent call last):
  File "<pyshell#17>", line 1in <module>
    getattr(s,'age')
AttributeError: 'Stduent' object has no attribute 'age'
>>> class Student:
    def __init__(self,name):
        self.name = name

        
>>> a = Student('Kim')
>>> a.name
'Kim'
>>> setattr(a,'name','Bob')
>>> a.name
'Bob'
#定义类A
>>> class A:
    def __init__(self,name):
        self.name = name
    def sayHello(self):
        print('hello',self.name)

#测试属性和方法
>>> a.name
'小麦'
>>> a.sayHello()
hello 小麦

#删除属性
>>> delattr(a,'name')
>>> a.name
Traceback (most recent call last):
  File "<pyshell#47>", line 1in <module>
    a.name
AttributeError: 'A' object has no attribute 'name'
>>> class B: #定义类B
    def __call__(self):
        print('instances are callable now.')

        
>>> callable(B) #类B是可调用对象
True
>>> b = B() #调用类B
>>> callable(b) #实例b是可调用对象
True
>>> b() #调用实例b成功
instances are callable now.

变量操作

>>> globals()
{'__name__''__main__''__doc__'None'__package__'None'__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None'__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': [123456789], 'if_odd': <function if_odd at 0x03544F60>}
>>> def f():
    print('before define a ')
    print(locals()) #作用域内无变量
    a = 1
    print('after define a')
    print(locals()) #作用域内有一个a变量,值为1

    
>>> f
<function f at 0x03D40588>
>>> f()
before define a 
{} 
after define a
{'a'1}

交互操作

闭上眼睛都会用这两个啦

文件操作

# t为文本读写,b为二进制读写
>>> a = open('test.txt','rt')
>>> a.read()
'some text'
>>> a.close()

下面介绍的内置函数对于我们写程序来说,绝对会是点睛之笔,一个字牛!!

编译执行

>>> #流程语句使用exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,'','exec')
>>> exec (compile1)
0
1
2
3
4
5
6
7
8
9


>>> #简单求值表达式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval')
>>> eval(compile2)
10
>>> eval('pow(2,2)')# 计算字符串中有效的表达式,
4
>>> eval('2 + 2')
4
>>> eval("n + 4")
85
# 将字符串转成相应的对象(如list、tuple、dict和string之间的转换
>>> a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>> b = eval(a)
>>> b
[[12], [34], [56], [78], [90]]
>>> a = "{1:'xx',2:'yy'}"
>>> c = eval(a)
>>> c
{1'xx'2'yy'}
>>> a = "(1,2,3,4)"
>>> d = eval(a)
>>> d
(1234)

# 将利用反引号转换的字符串再反转回对象
>>> list1 = [1,2,3,4,5]
>>> `list1`
'[1, 2, 3, 4, 5]'
>>> type(`list1`)
<type 'str'>
>>> type(eval(`list1`))
<type 'list'>
>>> a = eval(`list1`)
>>> a
[12345]

>>> exec('a=1+2'#执行语句
>>> a
3
>>> a = 'some text'
>>> str(a)
'some text'
>>> repr(a)
"'some text'"

装饰器

>>> class C:
    def __init__(self):
        self._name = ''
    @property
    def name(self):
        """i'm the 'name' property."""
        return self._name
    @name.setter
    def name(self,value):
        if value is None:
            raise RuntimeError('name can not be None')
        else:
            self._name = value

            
>>> c = C()

>>> c.name # 访问属性
''
>>> c.name = None # 设置属性时进行验证
Traceback (most recent call last):
  File "<pyshell#84>", line 1in <module>
    c.name = None
  File "<pyshell#81>", line 11in name
    raise RuntimeError('name can not be None')
RuntimeError: name can not be None

>>> c.name = 'Kim' # 设置属性
>>> c.name # 访问属性
'Kim'

>>> del c.name # 删除属性,不提供deleter则不能删除
Traceback (most recent call last):
  File "<pyshell#87>", line 1in <module>
    del c.name
AttributeError: can't delete attribute
>>> c.name
'
Kim'
>>> class C:
    @classmethod
    def f(cls,arg1):
        print(cls)
        print(arg1)

        
>>> C.f('类对象调用类方法')
<class '__main__.C'>
类对象调用类方法

>>> c = C()
>>> c.f('类实例对象调用类方法')
<class '__main__.C'>
类实例对象调用类方法
# 使用装饰器定义静态方法
>>> class Student(object):
    def __init__(self,name):
        self.name = name
    @staticmethod
    def sayHello(lang):
        print(lang)
        if lang == 'en':
            print('Welcome!')
        else:
            print('你好!')

            
>>> Student.sayHello('en'#类调用,'en'传给了lang参数
en
Welcome!

>>> b = Student('Kim')
>>> b.sayHello('zh')  #类实例对象调用,'zh'传给了lang参数
zh
你好

学 Python 就来 PythonGuide:前往 github 地址

PythonGuide :「Python 学习 + 面试指南」一份涵盖大部分 Python 相关行业的程序员所需要掌握的核心知识。准备 Python 面试,来看 PythonGuide!


↙↙↙阅读原文可查看相关链接,并与作者交流