zoukankan      html  css  js  c++  java
  • day4-内置函数

    一、内置函数列表

    http://images2015.cnblogs.com/blog/720333/201608/720333-20160805221828434-1477884803.png

    二、常见内置函数用法

    由于python内置函数较多,在此总结一下部分常见的内置函数的用法:

    1. abs(x)
      功能:取数的绝对值
        1 >>> abs(0)
        2 0
        3 >>> abs(-5)
        4 5
        5 >>>
    2. all(interable)
      功能:判断可迭代对象中的每个元素,如果均为真(非0)则返回true,反之返回false
        1 >>> all([1,2,3])
        2 True
        3 >>> all([0,1,2,3])
        4 False
        5 >>>
    3. any(interable)
      功能:也是判断可迭代对象中的每个元素,不同的是只要有一个元素为真就返回true,反之返回false
        1 >>> any(['a','b','c'])
        2 True
        3 >>> any([])     #空列表为假
        4 False
        5 >>> any([0])
        6 False
        7 >>> any([0,1])
        8 True
        9 >>>
    4. bin(x)
      功能:把整数转换成二进制
        1 >>> bin(100)
        2 '0b1100100'
        3 >>> bin(1)
        4 '0b1'
        5 >>>
    5. bool(object)
      功能:判断对象,返回布尔值,为空或0则返回false,反之返回true
        1 >>> bool('x')
        2 True
        3 >>> bool('')
        4 False
        5 >>> bool(0)
        6 False
        7 >>>
    6. bytearray[source[, encoding[, errors]]]
      功能:把二进制字节转换成可以修改的数组(列表)
        1 >>> list1=bytearray('001',encoding='utf-8')
        2 >>> list1
        3 bytearray(b'001')
        4 >>> list1[0]   	#以列表方式访问元素,返回的是对应的ASCII码
        5 48
        6 >>> list1[0]=99 	#更新时也必须以ASCII码的形式来更新
        7 >>> list1
        8 bytearray(b'c01')	#更新后原列表变了
        9 >>>
    7. bytes([source[, encoding[, errors]]])
      功能:把字符串转换成字节,但不能修改内容
        1 >>> b = bytes("abcd",encoding="utf-8")
        2 >>> b
        3 b'abcd'
        4 >>> b[1]
        5 98
        6 >>> b[1]=99
        7 Traceback (most recent call last):
        8   File "<stdin>", line 1, in <module>
        9 TypeError: 'bytes' object does not support item assignment
    8. callable(object)
      功能:判断一个对象是否可以被调用,目前所知道的只有函数或类才可以通过调用符号()去调用。
        1 >>> def func1():
        2 ...     pass
        3 ...
        4 >>> callable(func1)
        5 True
        6 >>> a='test'
        7 >>> callable(a)
        8 False
    9. chr(x)
      功能:把ASCII中的数字转换成对应的字符
        1 >>> chr(98)
        2 'b'
    10. ord(x)
      功能:获取一个字符对应的ASCII码
        1 >>> ord('c')
        2 99
    11. dict(**kwarg)、dict(mapping, **kwarg)、dict(iterable, **kwarg)
      功能:生成一个字典
        1 >>> dict
        2 <class 'dict'>
        3 >>> dict({('address','Chengdu'),('Num','028')})  #传入一个set
        4 {'address': 'Chengdu', 'Num': '028'}
        5 >>> dict([('address','Chengdu'),('Num','028')])  #传入list
        6 {'address': 'Chengdu', 'Num': '028'}
        7 >>> dict([['address','Chengdu'],['Num','028']])
        8 {'address': 'Chengdu', 'Num': '028'}
        9 >>> dict((('address','Chengdu'),('Num','028')))  #传入元组
       10 {'address': 'Chengdu', 'Num': '028'}
       11 >>>
    12. dir(object)
      功能:查看一个对象的方法
        1 >>> a=dict((('address','Chengdu'),('Num','028')))
        2 >>> dir(a)
        3 ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__'
        4 , '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__',
        5  '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '
        6 __lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__seta
        7 ttr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'co
        8 py', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update
        9 ', 'values']
    13. divmod(a,b)
      功能:地板除,获得一个元组,元组第一个元素是商,第二个元素是余数。
        1 >>> divmod(9,2)
        2 (4, 1)
    14. enumerate(iterable,start=0)
      功能:遍历一个iterable中,逐个返回索引和相应的元素(一个enumerate对象),start参数可设置索引起始值,默认从0开始
        1 >>> test='abcd'
        2 >>> for index,item in enumerate(test):
        3 ...     print(index,item)
        4 ...
        5 0 a
        6 1 b
        7 2 c
        8 3 d
        9 >>> print(list(enumerate(test)))
       10 [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
       11 >>> print(list(enumerate(test,start=2)))    #start参数人为设定起始索引值,默认从0开始
       12 [(2, 'a'), (3, 'b'), (4, 'c'), (5, 'd')]
       13 >>> print(dict(enumerate(test)))
       14 {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
    15. eval(expression, globals=None, locals=None)
      功能:进行简单的数学运算,对于符合其他特征不可计算的字符串,进行类型转换,比如可以把符合特征的字符串转换成int类型,list,tuple,dict等。
        1 >>> eval('100')
        2 100
        3 >>> type(eval('100'))
        4 <class 'int'>
        5 >>> eval("[1,2,3]")
        6 [1, 2, 3]
        7 >>> eval("(1,2,3)")
        8 (1, 2, 3)
        9 >>> eval("{1:'name',2:'male',3:'age'}")
       10 {1: 'name', 2: 'male', 3: 'age'}
    16. filter(function, iterable)
      功能:根据function定义的过滤条件,筛选出Iterable中符合条件的数据。
        1 >>> a=filter(lambda x:x %2 == 0, [0,1,2,3,4])
        2 >>> print(a)
        3 <filter object at 0x0000000001E9BE48>   #经filter处理后返回的是一个filter对象
        4 >>> for i in a:
        5 ...     print(i)
        6 ...
        7 0
        8 2
        9 4
    17. map(function, iterable)
      功能:接收参数function和可迭代对象iterable,对于每个迭代的元素一一进行函数运算,然后返回相应的结果(简单理解为一对一映射处理)
        1 >>> def func1(x):
        2 ...     return x * 2
        3 ...
        4 >>> rs=map(func1,range(5))
        5 >>> for i in rs:
        6 ...     print(i)
        7 ...
        8 0
        9 2
       10 4
       11 6
       12 8
       13 >>> rs
       14 <map object at 0x00000000021DBE10>
    18. reduce(function,iterable,initializer)
      功能:将一个带有两个参数的方法累计应用到一个可迭代的对象的元素上(function必须接收两个参数,遍历可迭代对象的元素,把上一次计算的结果作为下一次计算的第一个参数),以便把可迭代对象规约为一个单一的值,即大数据中的reduce规约计算。其中第三个参数初始值是可选的,如果给出了初始值,则把初始值作为第一个计算的第一个参数。

        1 >>> def f(x,y):
        2 ...     return x+y
        3 ...
        4 >>> reduce(f,[1,3,5,7,9])
        5 Traceback (most recent call last):
        6   File "<stdin>", line 1, in <module>
        7 NameError: name 'reduce' is not defined
        8 >>> from functools import reduce   #注意这里需要先导入后才能使用
        9 >>> reduce(f,[1,3,5,7,9])
       10 25
       11 >>> reduce(f,[1,3,5,7,9],100)      #给出初始值100
       12 125
      计算过程如下:
    19. 先计算头两个元素:f(1, 3),结果为4;
      再把结果和第3个元素计算:f(4, 5),结果为9;
      再把结果和第4个元素计算:f(9, 7),结果为16;
      再把结果和第5个元素计算:f(16, 9),结果为25;
      由于没有更多的元素了,计算结束,返回结果25。
      典型的应用场景是:凡是要对一个可迭代独享进行操作的,并且要有一个统计结果的,能够用循环或者递归方式解决的问题,一般情况下都可以用reduce方式实现(比如统计一个集合中key重复的次数)。

    20. float
      功能:把一个数字形式的字符串转换为浮点类型的数据。
        1 >>> float('a')
        2 Traceback (most recent call last):
        3   File "<stdin>", line 1, in <module>
        4 ValueError: could not convert string to float: 'a'   #a不是数字形式,无法转换
        5 >>>
        6 >>> float('1')
        7 1.0
        8 >>> float('1.23')
        9 1.23
    21. fronzenset(interable)
      功能:把一个可迭代对象转换为一个不可变的集合(双重特性,首先是符合集合的特性,其次是不可变)
        1 >>> res=frozenset([1,1,2,2,3])
        2 >>> res
        3 frozenset({1, 2, 3})  #集合中的元素不可重复,符合集合特征
        4 >>> res.add(4)  #不能针对该集合增加元素,不可变
        5 Traceback (most recent call last):
        6   File "<stdin>", line 1, in <module>
        7 AttributeError: 'frozenset' object has no attribute 'add'
        8 >>> dir(res)  #没有可变方法
        9 ['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '_
       10 _eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__ini
       11 t__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__',
       12 '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__r
       13 or__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__'
       14 , '__subclasshook__', '__xor__', 'copy', 'difference', 'intersection', 'isdisjoi
       15 nt', 'issubset', 'issuperset', 'symmetric_difference', 'union']
       16 >>>
    22. globals()
      功能:返回程序中所有的变量键值对(key 变量名, value 变量值,全局变量)
        1 >>> def foo(x):
        2 ...     global a
        3 ...     a=10
        4 ...     b=20
        5 ...     print(globals())
        6 ...
        7 >>> foo()
        8 Traceback (most recent call last):
        9   File "<stdin>", line 1, in <module>
       10 TypeError: foo() missing 1 required positional argument: 'x'
       11 >>> foo(1)
       12 {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <cl
       13 ass '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {
       14 }, '__builtins__': <module 'builtins' (built-in)>, 'f': <function f at 0x0000000
       15 001D23E18>, 'reduce': <built-in function reduce>, 'res': frozenset({1, 2, 3}), '
       16 test': <function test at 0x00000000023DAEA0>, 'foo': <function foo at 0x00000000
       17 02543840>, 'a': 10}   #定义的全局变量已经获取打印到
       18 
       19 >>> def foo2():
       20 ...     global a
       21 ...     a=100
       22 ...     print(globals().get('a'))  #直接获取全局变量的值
       23 ...
       24 >>> foo2()
       25 100
    23. locals()
      功能:与globals()类似,但返回的是局部变量
        1 >>> def foo(x):
        2 ...     a='hehe'
        3 ...     print(locals())
        4 ...
        5 >>> foo(1)
        6 {'a': 'hehe', 'x': 1}
        7 >>>
    24. hash()
      功能:根据一定的算法生成固定的映射结果,相同的输入生成相同的输出
        1 >>> hash('xy')
        2 6325275833896794579
        3 >>> hash('xy')
        4 6325275833896794579
        5 >>> hash('100')
        6 -93280025000303673
        7 >>> hash(100)
        8 100
        9 >>>
      这里需要注意的是它的应用场景hash函数把复杂的key(如中文)转换为固定的值存储,以便后续的复杂处理(查找,更新等),因为处理映射后的value更容易
    25. max(iterable)
      功能:返回一个可迭代对象的最大值
        1 >>> max((1,2,3))
        2 3
        3 >>> max({1,2,6})
        4 6
    26. min(interable)
      功能:返回一个可迭代对象的最小值
        1 >>> max((1,2,3))
        2 3
        3 >>> max({1,2,6})
        4 6
    27. input()
      功能:输入字符串
        1 >>> input(':')
        2 :hehe
        3 'hehe'
    28. list()
      功能:把其他的序列转换成列表
        1 >>> list({1,2,3})
        2 [1, 2, 3]
    29. set()
      功能:把其他的序列(可迭代对象)转换成集合
        1 >>> set({1:'a',2:'b'})
        2 {1, 2}
        3 >>> set(range(5))
        4 {0, 1, 2, 3, 4}
    30. hex()
      功能:转换十六进制
        1 >>> hex(16)
        2 '0x10'
        3 >>>
    31. oct()
      功能:转换八进制
        1 >>> oct(8)
        2 '0o10'
        3 >>> oct(7)
        4 '0o7'
    32. sorted(iterable[, key][, reverse])
      功能:对一个序列进行排序
        1 >>> a={1:'a',2:'c',3:'b'}
        2 >>> sorted(a)  #默认只是排序key
        3 [1, 2, 3]
        4 >>> sorted(a.items()) #a.items返回的是包含键值对元组的列表,这里还是按key排序
        5 [(1, 'a'), (2, 'c'), (3, 'b')]
        6 >>> sorted(a.items(),key=lambda x:x[1]) #指定键值对中的value作为排序的key,因此按value来排序
        7 [(1, 'a'), (3, 'b'), (2, 'c')]
        8 >>> print(a.items())
        9 dict_items([(1, 'a'), (2, 'c'), (3, 'b')])
    33. zip(*iterables)
      功能:组合两个对象(zip中文拉链的意思),一一对应起来(如果有一个序列的个数更少,则按少的那个来)。
        1 >>> a=[1,2,3]
        2 >>> b={'a','b'}
        3 >>> for i in zip(a,b):
        4 ...     print(i)
        5 ...
        6 (1, 'a')
        7 (2, 'b')
        8 >>>

    34. __import__(name, globals=None, locals=None, fromlist=(), level=0)
      功能:当导入的模块是一个字符串时,用__import__()
        1 >>> import os
        2 >>> __import__('os')
        3 <module 'os' from 'C:\Program Files (x86)\python3.6.1\lib\os.py'>

  • 相关阅读:
    threejs 通过bufferGeometry处理每一个点的位置和颜色
    nodejs通过buffer传递数据到前端,前端通过arraybuffer接收数据
    ubuntu 通过ssh上传/下载服务器文件
    前端通过浏览器导出文件并下载
    前端imageBuffer设置图片src(后端到前端直传buffer)
    一个FLAG #17# 测试STL
    一个FLAG #16# 优先队列
    一个FLAG #15# 团队队列
    一个FLAG #14# The SetStack Computer
    一个FLAG #13# V字型数列
  • 原文地址:https://www.cnblogs.com/linupython/p/7679771.html
Copyright © 2011-2022 走看看