Built-in Functions
abs()  dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() insubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() _import_()
complex() hasattr() max() round()  
delattr() hash() memoryview() set()  
  • abs()  取绝对值
  • dict()  把一个数据转成字典
  • help()  帮助
  • min()  从列表中取出最小数
>>> a  = [1,4,5,-1,3]
>>> min(a)
-1
  • max()  从列表中取出最大数
>>> a  = [1,4,5,-1,3]
>>> max(a)
5
  • all()  如果bool(x)为True,即x中所有元素均为True,all(x)为True。如果x是可循环的(列表为可循环的),all(x)也返回True。

空列表或列表内元素全为True,all()为True。

#一种特殊情况
>>> bool([])
False
>>> all([])
True
  • any()
#和all相反,只要有列表中有一个元素为True,any即为True
>>> any([False,0])
False
>>> any([False,0,1])
True
>>> any([])
False
  • dir()  打印当前程序中存在的所有变量
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__'] #系统自带变量
>>> dir(__builtins__) #打印所有的内置模块
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
  • vars()  打印当前所有变量名及其对应的值
>>> vars()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 's': frozenset({2, 3, 4, 5}), 'f': <function f at 0x000002C11182F7B8>, 'lis': [1, 2, 3]}
  • locals()  在函数里面运行,打印函数里所有的局部变量名及其值
>>> def f():
... n = 3
... print(locals())
...
>>> f()
{'n': 3}
  • globals()  打印所有全局变量名及其值
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 's': frozenset({2, 3, 4, 5}), 'f': <function f at 0x000002C1118359D8>, 'lis': [1, 2, 3]}
  • hex()  将数字转换成十六进制
  • slice()  切片:相当于提前定义好切片要求
>>> l = list(range(10))
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> s = slice(1,7,2)
>>> s
slice(1, 7, 2)
>>> l[1:7:2]
[1, 3, 5]
>>> l[s]
[1, 3, 5]
  • divmod()  取整除和余数
>>> 10//3
3
>>> 10/3
3.3333333333333335
>>> 10%3
1
>>> divmod(10,3) #10除以3
(3, 1) #返回(商,余数)
  • id()  查内存地址
  • sorted()  排序,默认由小到大
#列表排序,和sort功能一致
>>> l = list(range(10))
>>> l[4] = 99
>>> l
[0, 1, 2, 3, 99, 5, 6, 7, 8, 9]
>>> sorted(l)
[0, 1, 2, 3, 5, 6, 7, 8, 9, 99]
>>> l
[0, 1, 2, 3, 99, 5, 6, 7, 8, 9]
>>> l.sort()
>>> l
[0, 1, 2, 3, 5, 6, 7, 8, 9, 99]
#字典排序
>>> d = {}
>>> for i in range(20):
... d[i] = i-50
...
>>> d #字典本身无序
{0: -50, 1: -49, 2: -48, 3: -47, 4: -46, 5: -45, 6: -44, 7: -43, 8: -42, 9: -41, 10: -40, 11: -39, 12: -38, 13: -37, 14: -36, 15: -35, 16: -34, 17: -33, 18: -32, 19: -31}
>>> d.items() #生成元组同样无序
dict_items([(0, -50), (1, -49), (2, -48), (3, -47), (4, -46), (5, -45), (6, -44), (7, -43), (8, -42), (9, -41), (10, -40), (11, -39), (12, -38), (13, -37), (14, -36), (15, -35), (16, -34), (17, -33), (18, -32), (19, -31)])
>>> sorted(d.items()) #默认从小到大排序
[(0, -50), (1, -49), (2, -48), (3, -47), (4, -46), (5, -45), (6, -44), (7, -43), (8, -42), (9, -41), (10, -40), (11, -39), (12, -38), (13, -37), (14, -36), (15, -35), (16, -34), (17, -33), (18, -32), (19, -31)]
>>> sorted(d.items(),key= lambda x:x[1]) #按照value值从小到大排序
[(0, -50), (1, -49), (2, -48), (3, -47), (4, -46), (5, -45), (6, -44), (7, -43), (8, -42), (9, -41), (10, -40), (11, -39), (12, -38), (13, -37), (14, -36), (15, -35), (16, -34), (17, -33), (18, -32), (19, -31)]
>>> d[0] = 399
>>> sorted(d.items(),key=lambda x:x[1]) #按照value值从小到大排序
[(1, -49), (2, -48), (3, -47), (4, -46), (5, -45), (6, -44), (7, -43), (8, -42), (9, -41), (10, -40), (11, -39), (12, -38), (13, -37), (14, -36), (15, -35), (16, -34), (17, -33), (18, -32), (19, -31), (0, 399)]
>>> sorted(d.items(),key=lambda x:x[1],reverse=True) #按照value值从大到小排序
[(0, 399), (19, -31), (18, -32), (17, -33), (16, -34), (15, -35), (14, -36), (13, -37), (12, -38), (11, -39), (10, -40), (9, -41), (8, -42), (7, -43), (6, -44), (5, -45), (4, -46), (3, -47), (2, -48), (1, -49)]
  • reversed()  和sorted()一样,不过是默认由大到小
  • ascii()  返回unico编码
>>> s = 'abcd路飞'
>>> s
'abcd路飞'
>>> ascii(s) #返回s的Unicode编码
"'abcd\\u8def\\u98de'"
  • enumerate()  枚举,返回索引
  • input()  输入
  • oct()  转成八进制
  • bin()  转成二进制
  • eval()  按解释器的规则把单行字符串转成代码运行
#将字符串转换成公式进行运算
>>> s = '1+3/2'
>>> s
'1+3/2'
>>> eval(s)
2.5
#执行单行代码
>>> eval('print("hello world")')
hello world
#不能执行多行代码
>>> code = '''
... if 3>5 :
... print('3 is bigger than 5')
... else:
... print('dddd')
... '''
>>> code
"\nif 3>5 :\n\tprint('3 is bigger than 5')\nelse:\n\tprint('dddd')\n\n\n"
>>> eval(code)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 2
if 3>5 :
^
SyntaxError: invalid syntax
  • exec()  能运行多行代码,但是没有返回值
#exec()能运行多行代码但无返回值
>>> code = '''
... def foo():
... print('run foo')
... return 1234
... foo()
... '''
>>> res = exec(code)
run foo
>>> print('res',res)
res None
#运行单行代码与eval()对比
>> res1 = eval("1+3+3")
>>> res2 = exec("1+3+3")
>>> print('res',res1,res2)
res 7 None
  • int()  转换成整数类型
  • open()  打开文件open(file='', mode='',encoding='')
  • str()  转换成字符串类型
  • bool()  判断True or False,只有0是False
  • ord()  返回字符串在ASCII码里的值
>>> ord('a')
97
  • chr()  返回ASCII码值对应的字符串
>>> chr(97)
'a'
  • sum()
>>> a = [1,4,5,-1,3,0]
>>> a
[1, 4, 5, -1, 3, 0]
>>> sum(a) #将列表中所有元素加起来求和
12
  • bytearray()
    1. 一般用于修改长字符串,短字符串可改成列表然后进行修改。
    2. 可将字符串在原地址上修改,但字符串中修改的个别元素的地址会发生变化。
>>> s = 'abcd路飞'
>>> id(s)
1496733953552
>>> s = s.encode('gbk')
>>> s
b'abcd\xc2\xb7\xb7\xc9'
>>> s = bytearray(s) #字符串变成bytearray之后能修改
>>> s
bytearray(b'abcd\xc2\xb7\xb7\xc9')
>>> s[4]
194
>>> s[4] = 233
>>> s
bytearray(b'abcd\xe9\xb7\xb7\xc9')
>>> s = s.decode('gbk')
>>> s
'abcd榉飞'
>>> id(s) #在原地址上修改
1496733953552
  • map()
>>> map(lambda x:x*x,[1,2,3,4,5])
<map object at 0x0000015C7C561080>
>>> list(map(lambda x:x*x,[1,2,3,4,5]))
[1, 4, 9, 16, 25]
  • filter()  过滤
>>> filter(lambda x:x>3,[1,2,3,4,5])  #筛选出满足lambda条件的元素
<filter object at 0x0000015C7C561048>
>>> list(filter(lambda x:x>3,[1,2,3,4,5]))
[4, 5]
  • reduce()
>>> import functools
>>> functools.reduce(lambda x,y:x+y,[1,2,3,4,5,6,7,8]) #求和
36
>>> functools.reduce(lambda x,y:x*y,[1,2,3,4,5,6,7,8]) #求乘积
40320
>>> functools.reduce(lambda x,y:x+y,[1,2,3,4,5,6,7,8],3) #求和加上最后一项
39
  • pow()  求次方   pow(a, b) = a**b
  • bytes()  换成byte类型
  • float()  换成浮点类型
  • print()  打印   print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)  flush以后会用到,这里先不讲
>>> s = 'hey, my name is alex\n, from Shanghai'
>>> print(s)
hey, my name is alex
, from Shanghai
>>> print(s,end='.')
hey, my name is alex
, from Shanghai.>>> #在最后会默认加一个\n
...
>>> print(s,end='|') #end是以什么结尾
hey, my name is alex
, from Shanghai|>>>
>>> print('haifeng','gangniang',sep='->') #sep是以什么连接两个字符串
haifeng->gangniang
#写入文件
msg = '又回到最初的原点'
f = open('print_tofile.txt', 'w')
print(msg, '记忆中你青涩的脸', sep='|', end='.', file=f)#不会在最后自带换行,重复本行命令,可连着写入
  • tuple()  变成元组
  • callable()  判断是否可调用
>>> def f():
... pass
...
>>> callable(f) #带(),即是函数,就可调用,其余不可调用
True
>>> lis = [1,2,3]
>>> callable(lis)
False
  • format()  格式化
  • len()  获取长度
  • type()  类型
  • frozenset()  冷冻的集合,即为不可变的集合
>>> s = {1,2,3,4,5}
>>> s.discard(1)
>>> s
{2, 3, 4, 5}
>>> s = frozenset(s)
>>> s.discard(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'discard'
  • list()  列表
  • range()  循环
  • repr()   把变量值显示成字符串形式
>>> s
frozenset({2, 3, 4, 5})
>>> repr(s)
'frozenset({2, 3, 4, 5})'
  • zip()  将两个列表元素一一对应生成元组,无对应元素的多余部分被舍弃
>>> a = [1,2,3,4,5]
>>> b = ['a','b','c']
>>> a
[1, 2, 3, 4, 5]
>>> b
['a', 'b', 'c']
>>> zip(a,b)
<zip object at 0x000002C1118C4FC8>
>>> list(zip(a,b))
[(1, 'a'), (2, 'b'), (3, 'c')]
  • complex()  把数字变成复数
>>> complex(3,5)
(3+5j)
  • round()  保留几位小数,默认不保留小数部分
>>> round(1.234567)
1
>>> round(1.234567,2)
1.23
  • hash()  把字符串变成数字
#只要不重启,数字不会重复
>>> hash('abcd')
6166213067681790707
>>> hash('abcd')
6166213067681790707
  • set()  把列表变成集合
>>> set([1,2,3,4])
{1, 2, 3, 4}

后面讲模块会讲到:_import_()

后面面向对象再讲:next()  object()  staticmethod()  isinstance()  property()  classmethod()

delattr()  hasattr()  getattr()  setattr()  四剑客放在后面一起讲

memoryview()  基本用不到,用于大数据处理

compile()  编译代码用,现在用不到,讲模板引擎的时候可能会用到

Python全栈之路----函数----内置方法的更多相关文章

  1. Python全栈之路----函数----返回值

    函数外部的代码想要获取函数的执行结果,就可以在函数里用return语句,把结果返回. def stu_register(name,age,course='PY',country='CN'): prin ...

  2. Python全栈之路----函数----高阶函数

    变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另一函数作为参数,这种函数就称之为高阶函数. 只需满足以下任意一个条件,即是高阶函数: 接收一个或多个函数作为输入 def func(x, ...

  3. Python全栈之路----函数进阶----名称空间

    又名name space,顾名思义就是存放名字的地方,存什么名字呢?举例说明,若变量x=1,1存放于内存中,那名字x存放在哪里呢?名称空间正是存放名字x与1绑定关系的=地方 名称空间共3种,分别如下 ...

  4. Python全栈之路----函数----局部变量

    全局变量是定义在函数外部以及代码的变量,全局能用. 局部变量就是定义在函数里的变量,只能在局部生效. 在函数内部,可以引用全局变量. 如果全局和局部都有一个名字相同的变量,在函数内会优先调用函数内的局 ...

  5. Python全栈之路----函数进阶----作用域的查找空间

    n = 10 def func(): n = 20 print('func:',n) def func2(): n = 30 print('func2:',n) def func3(): print( ...

  6. Python全栈之路----函数进阶----装饰器

    Python之路,Day4 - Python基础4 (new版) 装饰器 user_status = False #用户登录后改为True def login(func): #传入想调用的函数名 de ...

  7. Python全栈之路----函数----作用域

    Python中,一个函数就是一个作用域. 局部变量放置在其作用域中,根据作用域来区分,函数属于你,函数属于我. 定义完成后,作用域已经生成,使用时顺着作用域链向上查找. 函数定义完成后,不管被在哪儿被 ...

  8. Python全栈之路----函数进阶----迭代器

    我们已经知道,可以直接作用于 for 循环的数据类型有以下几种: 一类是集合数据类型,如 list , tuple , dict , set ,str 等: 一类是 generator ,包括生成器和 ...

  9. Python全栈之路----函数

    基本介绍 定义:函数是指将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可. 编程中的函数在英文中有很多不同的叫法:在BASIC中叫做subroutine(子过程或 ...

随机推荐

  1. poj1985和poj1849(树的直径)

    题目传送门:poj1985 树是连通无环图,树上任意两点之间的路径是唯一的.定义树上任 意两点u, v的距离为u到v路径上边权的和.树的直径MN为树上最长路 径,即点M和N是树上距离最远的两个点. 题 ...

  2. kvm键盘使用

    在新建导向的时候最后一步之前,选择查看细节那里,在desplay的地方选择VNC server ,再在keyboard地方选择us-en,这下进入安装界面就可以了.

  3. (转) Ensemble Methods for Deep Learning Neural Networks to Reduce Variance and Improve Performance

    Ensemble Methods for Deep Learning Neural Networks to Reduce Variance and Improve Performance 2018-1 ...

  4. js运行机制详解:event loop

    总结 阮一峰老师的博客 一.为什么JavaScript是单线程 JavaScript语言的一大特点就是单线程 那么,为什么JavaScript不能有多个线程呢?这样能提高效率啊. JavaScript ...

  5. pycurl安装

    pip install pycurl 出现:Could not run curl-config: [Errno 2] No such file or directory: 'curl-config': ...

  6. 雷林鹏分享:jQuery EasyUI 数据网格 - 条件设置行背景颜色

    jQuery EasyUI 数据网格 - 条件设置行背景颜色 本教程将向您展示如何根据一些条件改变数据网格(datagrid)组件的行样式.当 listprice 值大于 50 时,我们将为该行设置不 ...

  7. 【你不一定知晓的】C#取消异步操作

    [你不一定知晓的]C#取消异步操作 在.Net和C#中运行异步代码相当简单,因为我们有时候需要取消正在进行的异步操作,通过本文,可以掌握 通过CancellationToken取消任务(包括non-c ...

  8. js实现下雪雪花特效

    两种下雪特效: 1. <script type="text/javascript"> (function($){ $.fn.snow = function(option ...

  9. PAT 1092 To Buy or Not to Buy

    1092 To Buy or Not to Buy (20 分)   Eva would like to make a string of beads with her favorite colors ...

  10. 一个简单的CD/CI流程思考,续

    经过各种优化,最终一个非常简单的pipeline出现了,图中没有包含单元测试及静态代码检查的部分,有时间补上.至少实现了提交即构建,也能迅速反馈给开发者. 但是最大的问题是,研发团队还是习惯依赖于部署 ...