本篇主要内容:内置函数

函数

参考:https://docs.python.org/3.5/library/functions.html

内置函数列表

一、数学运算类

  1. abs(x)求绝对值
  1. >>> abs(-)
  1. complex([real[, imag]])创建一个复数
  1. >>> complex()
  2. (+0j)
  3. >>>
  1. divmod(a, b)分别取商和余数注意:整型、浮点型都可以
  1. >>> divmod(,)
  2. (, )
  1. float([x])将一个字符串或数转换为浮点数。如果无参数将返回0.0
  1. >>> float("3.2")
  2. 3.2
  1. int([x[, base]])将一个字符转换为int类型,base表示进制
  1. >>> int("", base=)
  1. pow(x, y[, z])返回xy次幂
  1. >>> pow(,,)
  2.  
  3. >>> pow(,,) # 8的2次方整除10的余数
  1. range([start], stop[, step])产生一个序列,默认从0开始
  1. >>> for i in range(): #默认输出
  2. ... print(i)
  3. ...
  4.  
  5. >>>
  6. >>> for i in range(,): #指定起始值
  7. ... print(i)
  8. ...
  9.  
  10. >>>
  11. >>> for i in range(,,): #指定起始值和步进长度
  12. ... print(i)
  13. ...
  14.  
  15. >>>
  1. round(x[, n])四舍五入
  1. >>> round(1.1)
  2.  
  3. >>> round(1.5)
  1. sum(iterable[, start])对集合求和
  1. >>> sum([,,,,])
  1. oct(x)将一个数字转化为8进制
  1. >>> oct()
  2. '0o12'
  1. hex(x)将整数x转换为16进制字符串
  1. >>> hex()
  2. '0x1a'
  1. chr(i)返回整数i对应的ASCII字符
  1. >>> chr()
  2. 'A'
  1. bin(x)将整数x转换为二进制字符串
  1. >>> bin()
  2. '0b10000000000'
  1. bool([x])将x转换为Boolean类型
  1. >>> bool([]) # 空列表
  2. False
  3. >>> bool(()) # 空元组
  4. False
  5. >>> bool({}) # 空字典
  6. False
  7. >>> bool(-)
  8. True
  9. >>> bool()
  10. False
  11. >>> bool()
  12. True
  13. >>>

二、集合操作类

  1. format(value [, format_spec]) 格式化输出字符串格式化的参数顺序从0开始,如“I am {0},I like {1}”
  1. >>> print('We are the {} who say "{}!"'.format('guys', 'Hi'))
  2. We are the guys who say "Hi!"
  1. enumerate(sequence [, start = 0]) 返回一个可枚举的对象,该对象的next()方法将返回一个tuple
  1. t = (,,,,,)
  2. for i in enumerate(t): # enumerate() 为可迭代的对象添加序号,默认从0开始
  3. print(i)
  4.  
  5. (, )
  6. (, )
  7. (, )
  8. (, )
  9. (, )
  10. (, )
  1. iter(o[, sentinel]) 生成一个对象的迭代器,第二个参数表示分隔符
  1. >>> s = 'abc'
  2. >>> it = iter(s)
  3. >>> it
  4. <iterator object at 0x00A1DB50>
  5. >>> next(it)
  6. 'a'
  7. >>> next(it)
  8. 'b'
  9. >>> next(it)
  10. 'c'
  11. >>> next(it)
  12. Traceback (most recent call last):
  13. File "<stdin>", line , in ?
  14. next(it)
  15. StopIteration
  1. max(iterable[, args...][key]) 返回集合中的最大值
  1. >>> max([,,,,])
  1. min(iterable[, args...][key]) 返回集合中的最小值
  1. >>> min([,,,,])
  1. dict([arg]) 创建数据字典
  1. >>> dict([('sape', ), ('guido', ), ('jack', )])
  2. {'sape': , 'jack': , 'guido': }
  1. list([iterable]) 将一个集合类转换为另外一个集合类
  1. >>> t = (,,,,)
  2. >>> type(t)
  3. <class 'tuple'>
  4. >>> li = list(t)
  5. >>> li
  6. [, , , , ]
  7. >>> type(li)
  8. <class 'list'>
  9. >>>
  1. set() set对象实例化
  1. >>> a = set('abracadabra')
  2. >>> b = set('alacazam')
  3. >>> a # a中不重复的元素
  4. {'a', 'r', 'b', 'c', 'd'}
  5. >>> a - b # a中存在b没有的
  6. {'r', 'd', 'b'}
  7. >>> a | b # a和b全部的元素
  8. {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
  9. >>> a & b # a中存在且b中存在
  10. {'a', 'c'}
  11. >>> a ^ b # 非(a中存在且b中存在)
  12. {'r', 'd', 'b', 'm', 'z', 'l'}
  1. frozenset([iterable]) 产生一个不可变的set
  1. >>> se = set("a,b,c,d,e,f")
  2. >>> se
  3. {'a', 'd', 'f', 'b', 'c', 'e', ','}
  4. >>> fse = frozenset(se)
  5. >>> fse
  6. frozenset({'b', 'c', 'e', 'd', ',', 'a', 'f'})
  7. >>> fse
  8. frozenset({'b', 'c', 'e', 'd', ',', 'a', 'f'})
  9. >>>
  1. str([object]) 转换为string类型
  1. >>> s = str("abc123")
  2. >>> s
  3. 'abc123'
  4. >>> type(s)
  5. <class 'str'>
  1. sorted(iterable[, cmp[, key[, reverse]]]) 队集合排序
  1. >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
  2. >>> for f in sorted(set(basket)):
  3. ... print(f)
  4. ...
  5. apple
  6. banana
  7. orange
  8. pear
  1. tuple([iterable]) 生成一个tuple类型
  1. >>> li = ["Hello","World"]
  2. >>> li
  3. ['Hello', 'World']
  4. >>> tuple(li)
  5. ('Hello', 'World')
  6. >>> t = tuple(li)
  7. >>> t
  8. ('Hello', 'World')
  9. >>> type(t)
  10. <class 'tuple'>
  11. >>>
  1.  

三、逻辑判断类

  1. all(iterable) 集合中的元素都为真的时候为真;特别的,若为空串返回为True
  1. >>> all([,,-])
  2. True
  3. >>> all([,,])
  4. False
  5. >>> all([,,[]])
  6. False
  7. >>> all([,,{}])
  8. False
  1. any(iterable) 集合中的元素有一个为真的时候为真;特别的,若为空串返回为False
  1. >>> any([,{},[],])
  2. True

四、反射

  1. eval(expression [, globals [, locals]])   计算表达式expression的值
  1. >>> eval("2 + 3 * 5 + 1 - 2")
  2.  
  3. >>>
  1. exec() 执行一个存储在字符串或者文件中的python语句
  1. >>> exec 'print "Hello World"'
  2. Hello World
  1. filter(function, iterable) 构造一个序列,等价于[ item for item in iterable if function(item)]
    参数function:返回值为TrueFalse的函数,可以为None
    参数iterable:序列或可迭代对象
  1. # filter函数
  2. def f1(x):
  3. if x > :
  4. return True
  5. else:
  6. return False
  7. ret = filter(f1, [,,,])
  8. for i in ret:
  9. print(i)
  1. getattr(object, name [, defalut]) 获取一个类的属性
  1. globals() 返回一个描述当前全局符号表的字典
  1. hasattr(object, name) 判断对象object是否包含名为name的特性
  1. hash(object) 如果对象object为哈希表类型,返回对象object的哈希值
  1. id(object) 返回对象的唯一标识
  1. >>> s = "Hello"
  2. >>> id(s)
  1. isinstance(object, classinfo) 判断object是否是class的实例
  1. >>> isinstance(s, str)
  2. True
  1. issubclass(class, classinfo) 判断是否是子类
  1. len(s) 返回集合长度
  1. >>> len(s)
  1. locals() 返回当前的变量列表
  1. map(function, iterable, ...) 遍历每个元素,执行function操作
  1. ret = map(lambda y: y > , [, , ])
  2. for i in ret:
  3. print(i)
  1. next(iterator[, default])   迭代出下一个元素
  1. object()   基类
  1. reload(module) 重新加载模块
  1. setattr(object, name, value) 设置属性值
  1. repr(object)   将一个对象变幻为可打印的格式
  1. slice()
     
  1. staticmethod 声明静态方法,是个注解
  1. super(type[, object-or-type]) 引用父类
  1. type(object) 返回该object的类型
  1. >>> s = "Hello"
  2. >>> type(s)
  3. <class 'str'>
  1. vars([object]) 返回对象的变量
  1. bytearray([source [, encoding [, errors]]]) 返回一个byte数组
    如果source为整数,则返回一个长度为source的初始化数组;
    如果source为字符串,则按照指定的encoding将字符串转换为字节序列;
    如果source为可迭代类型,则元素必须为[0 ,255]中的整数;
    如果source为与buffer接口一致的对象,则此对象也可以被用于初始化bytearray.
  1. s = "12dffgggggh"
  2. print(bytearray(s, encoding="utf-8"))
  3. bytearray(b'12dffgggggh')
  1. zip([iterable, ...]) 矩阵
  1. name = ['alex','eric']
  2. age = [,]
  3. result = zip(name,age)
  4. for i in result:
  5. print(i)
  6.  
  7. #执行结果
  8. ('alex', )
  9. ('eric', )

五、IO操作

  1. open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):
    打开文件
    参数filename:文件名称。
    参数mode'r'(读)、'w'(写)、'a'(追加)。
  1. # 只读
  2. f = open("log", "r")
  3.  
  4. # 只写模式(不可读:文件不存在则创建;存在则清空内容)
  5. f = open("log", "w")
  6.  
  7. # 只写模式(不可读,文件不存在则创建,存在则报错)
  8. f = open("log", "x")
  9.  
  10. # 追加模式(不存在则创建;存在则只追加内容)
  11. f = open("log", "s")
  1. input([prompt]) 获取用户输入
  1. inp = input("请输入图书编号")
  1. print 打印函数
  1. print("请输入图书编号")

六、其他

dir 用于按模块名搜索模块定义,它返回一个字符串类型的存储列表

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__'
, '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__'
, '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__'
, '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__s
izeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'ex
tend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
  1. help 调用内置函数的帮助系统
  1. >>> help(list)
  2. Help on class list in module builtins:
  3.  
  4. class list(object)
  5. | list() -> new empty list
  6. | list(iterable) -> new list initialized from iterable's items
    ...
    ...
    ...
  1.  

[Python笔记]第四篇:内置函数的更多相关文章

  1. Python笔记(二十一)_内置函数、内置方法

    内置函数 issubclass(class1,class2) 判断class1类是否为class2类的子类,返回True和False 注意1:类会被认为是自身的子类 >>>issub ...

  2. python基础12_匿名_内置函数

    一个二分查找的示例: # 二分查找 示例 data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35, 36, ...

  3. 【python】dir(__builtins__)查看python中所用BIF(内置函数)

    dir(__builtins__)查看python中所用BIF(内置函数)

  4. 查看python内部模块命令,内置函数,查看python已经安装的模块命令

    查看python内部模块命令,内置函数,查看python已经安装的模块命令 可以用dir(modules) 或者用 pip list或者用 help('modules') 或者用 python -m  ...

  5. Python学习(八) —— 内置函数和匿名函数

    一.递归函数 定义:在一个函数里调用这个函数本身 递归的最大深度:997 def func(n): print(n) n += 1 func(n) func(1) 测试递归最大深度 import sy ...

  6. python之路:进阶篇 内置函数

     li = [11, 22, 33] news = map(  li = [100, 2200, 3300] news = map(  [13, 24, 35] [11, 11, 11] [22, 4 ...

  7. 学习Python函数笔记之二(内置函数)

    ---恢复内容开始--- 1.内置函数:取绝对值函数abs() 2.内置函数:取最大值max(),取最小值min() 3.内置函数:len()是获取序列的长度 4.内置函数:divmod(x,y),返 ...

  8. python学习笔记(五)— 内置函数

    我们常用的‘’int,str,dict,input,print,type,len‘’都属于内置函数 print(all([1,2,3,4]))#判断可迭代的对象里面的值是否都为真 print(any( ...

  9. python 07篇 内置函数和匿名函数

    一.内置函数 # 下面这些要掌握 # len type id print input open # round min max filter map zip exec eval print(all([ ...

随机推荐

  1. 使用MyEclipse实现简单的Servlet程序

    1. 创建一个继承于GenericServlet的类 3. 重写Server方法 package cn.school; import java.io.IOException; import javax ...

  2. Mac OS X 程序员利器 – Homebrew安装与使用

    Mac OS X 程序员利器 – Homebrew安装与使用 Homebrew安装与使用 什么是Homebrew? Homebrew is the easiest and most flexible ...

  3. Y2错题解析

    数据流程图描述信息的来龙去脉和实际流程,反映信息在系统中流动.处理和存储的情况.程序结构图用来描述程序结构,一般由构成系统的要素和表达要素间关系的连线或箭头构成.因果图是一种发现问题"根本原 ...

  4. AFNetworking (3.1.0) 源码解析 <六>

    这次继续介绍文件夹Serialization下的类AFURLResponseSerialization.这次介绍就不拆分了,整体来看一下.h和.m文件. 协议AFURLResponseSerializ ...

  5. eclipse设置系统字体

    1. 打开eclipse-->Window-->Preferences-->General-->appearance-->Colors and Fonts, 点开后选择B ...

  6. [PWA] 10. Trigger a version update

    When the refersh button is clicked, we need to tell the waiting service worker to replace the curren ...

  7. LeetCode:Permutations(求全排列)

    Given a collection of numbers, return all possible permutations. For example,[1,2,3] have the follow ...

  8. Python下载漫画

    上午起来提不起劲,于是就用电脑看漫画,但是在线看漫画好烦,就想下下来看.一个一个点太麻烦,于是花了点时间用python写了个demo,把爱漫画的漫画下载下来,这样就可以随时随地看了.这也是我首次尝试用 ...

  9. Python 代码实现模糊查询

    Python 代码实现模糊查询 1.导语: 模糊匹配可以算是现代编辑器(如 Eclipse 等各种 IDE)的一个必备特性了,它所做的就是根据用户输入的部分内容,猜测用户想要的文件名,并提供一个推荐列 ...

  10. codevs2034 01串2

    /* 一开始认为是个水题 直接模拟 没想到只得了50分 一看数据吓niao了 模拟妥妥的TLE 实在不好优化了0.0(最快O(m)) 然后借鉴别人的 DP+神奇的输出 DP:状态:f[i][j] 前i ...