[Python笔记]第四篇:内置函数
本篇主要内容:内置函数
函数
参考:https://docs.python.org/3.5/library/functions.html
内置函数列表
一、数学运算类
- abs(x)求绝对值
- >>> abs(-)
- complex([real[, imag]])创建一个复数
- >>> complex()
- (+0j)
- >>>
- divmod(a, b)分别取商和余数注意:整型、浮点型都可以
- >>> divmod(,)
- (, )
- float([x])将一个字符串或数转换为浮点数。如果无参数将返回0.0
- >>> float("3.2")
- 3.2
- int([x[, base]])将一个字符转换为int类型,base表示进制
- >>> int("", base=)
- pow(x, y[, z])返回x的y次幂
- >>> pow(,,)
- >>> pow(,,) # 8的2次方整除10的余数
- range([start], stop[, step])产生一个序列,默认从0开始
- >>> for i in range(): #默认输出
- ... print(i)
- ...
- >>>
- >>> for i in range(,): #指定起始值
- ... print(i)
- ...
- >>>
- >>> for i in range(,,): #指定起始值和步进长度
- ... print(i)
- ...
- >>>
- round(x[, n])四舍五入
- >>> round(1.1)
- >>> round(1.5)
- sum(iterable[, start])对集合求和
- >>> sum([,,,,])
- oct(x)将一个数字转化为8进制
- >>> oct()
- '0o12'
- hex(x)将整数x转换为16进制字符串
- >>> hex()
- '0x1a'
- chr(i)返回整数i对应的ASCII字符
- >>> chr()
- 'A'
- bin(x)将整数x转换为二进制字符串
- >>> bin()
- '0b10000000000'
- bool([x])将x转换为Boolean类型
- >>> bool([]) # 空列表
- False
- >>> bool(()) # 空元组
- False
- >>> bool({}) # 空字典
- False
- >>> bool(-)
- True
- >>> bool()
- False
- >>> bool()
- True
- >>>
二、集合操作类
- format(value [, format_spec]) 格式化输出字符串格式化的参数顺序从0开始,如“I am {0},I like {1}”
- >>> print('We are the {} who say "{}!"'.format('guys', 'Hi'))
- We are the guys who say "Hi!"
- enumerate(sequence [, start = 0]) 返回一个可枚举的对象,该对象的next()方法将返回一个tuple
- t = (,,,,,)
- for i in enumerate(t): # enumerate() 为可迭代的对象添加序号,默认从0开始
- print(i)
- (, )
- (, )
- (, )
- (, )
- (, )
- (, )
- iter(o[, sentinel]) 生成一个对象的迭代器,第二个参数表示分隔符
- >>> s = 'abc'
- >>> it = iter(s)
- >>> it
- <iterator object at 0x00A1DB50>
- >>> next(it)
- 'a'
- >>> next(it)
- 'b'
- >>> next(it)
- 'c'
- >>> next(it)
- Traceback (most recent call last):
- File "<stdin>", line , in ?
- next(it)
- StopIteration
- max(iterable[, args...][key]) 返回集合中的最大值
- >>> max([,,,,])
- min(iterable[, args...][key]) 返回集合中的最小值
- >>> min([,,,,])
- dict([arg]) 创建数据字典
- >>> dict([('sape', ), ('guido', ), ('jack', )])
- {'sape': , 'jack': , 'guido': }
- list([iterable]) 将一个集合类转换为另外一个集合类
- >>> t = (,,,,)
- >>> type(t)
- <class 'tuple'>
- >>> li = list(t)
- >>> li
- [, , , , ]
- >>> type(li)
- <class 'list'>
- >>>
- set() set对象实例化
- >>> a = set('abracadabra')
- >>> b = set('alacazam')
- >>> a # a中不重复的元素
- {'a', 'r', 'b', 'c', 'd'}
- >>> a - b # a中存在b没有的
- {'r', 'd', 'b'}
- >>> a | b # a和b全部的元素
- {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
- >>> a & b # a中存在且b中存在
- {'a', 'c'}
- >>> a ^ b # 非(a中存在且b中存在)
- {'r', 'd', 'b', 'm', 'z', 'l'}
- frozenset([iterable]) 产生一个不可变的set
- >>> se = set("a,b,c,d,e,f")
- >>> se
- {'a', 'd', 'f', 'b', 'c', 'e', ','}
- >>> fse = frozenset(se)
- >>> fse
- frozenset({'b', 'c', 'e', 'd', ',', 'a', 'f'})
- >>> fse
- frozenset({'b', 'c', 'e', 'd', ',', 'a', 'f'})
- >>>
- str([object]) 转换为string类型
- >>> s = str("abc123")
- >>> s
- 'abc123'
- >>> type(s)
- <class 'str'>
- sorted(iterable[, cmp[, key[, reverse]]]) 队集合排序
- >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
- >>> for f in sorted(set(basket)):
- ... print(f)
- ...
- apple
- banana
- orange
- pear
- tuple([iterable]) 生成一个tuple类型
- >>> li = ["Hello","World"]
- >>> li
- ['Hello', 'World']
- >>> tuple(li)
- ('Hello', 'World')
- >>> t = tuple(li)
- >>> t
- ('Hello', 'World')
- >>> type(t)
- <class 'tuple'>
- >>>
三、逻辑判断类
- all(iterable) 集合中的元素都为真的时候为真;特别的,若为空串返回为True
- >>> all([,,-])
- True
- >>> all([,,])
- False
- >>> all([,,[]])
- False
- >>> all([,,{}])
- False
- any(iterable) 集合中的元素有一个为真的时候为真;特别的,若为空串返回为False
- >>> any([,{},[],])
- True
四、反射
- eval(expression [, globals [, locals]]) 计算表达式expression的值
- >>> eval("2 + 3 * 5 + 1 - 2")
- >>>
- exec() 执行一个存储在字符串或者文件中的python语句
- >>> exec 'print "Hello World"'
- Hello World
- filter(function, iterable) 构造一个序列,等价于[ item for item in iterable if function(item)]
参数function:返回值为True或False的函数,可以为None
参数iterable:序列或可迭代对象
- # filter函数
- def f1(x):
- if x > :
- return True
- else:
- return False
- ret = filter(f1, [,,,])
- for i in ret:
- print(i)
- getattr(object, name [, defalut]) 获取一个类的属性
- globals() 返回一个描述当前全局符号表的字典
- hasattr(object, name) 判断对象object是否包含名为name的特性
- hash(object) 如果对象object为哈希表类型,返回对象object的哈希值
- id(object) 返回对象的唯一标识
- >>> s = "Hello"
- >>> id(s)
- isinstance(object, classinfo) 判断object是否是class的实例
- >>> isinstance(s, str)
- True
- issubclass(class, classinfo) 判断是否是子类
- len(s) 返回集合长度
- >>> len(s)
- locals() 返回当前的变量列表
- map(function, iterable, ...) 遍历每个元素,执行function操作
- ret = map(lambda y: y > , [, , ])
- for i in ret:
- print(i)
- next(iterator[, default]) 迭代出下一个元素
- object() 基类
- reload(module) 重新加载模块
- setattr(object, name, value) 设置属性值
- repr(object) 将一个对象变幻为可打印的格式
- slice()
- staticmethod 声明静态方法,是个注解
- super(type[, object-or-type]) 引用父类
- type(object) 返回该object的类型
- >>> s = "Hello"
- >>> type(s)
- <class 'str'>
- vars([object]) 返回对象的变量
- bytearray([source [, encoding [, errors]]]) 返回一个byte数组
如果source为整数,则返回一个长度为source的初始化数组;
如果source为字符串,则按照指定的encoding将字符串转换为字节序列;
如果source为可迭代类型,则元素必须为[0 ,255]中的整数;
如果source为与buffer接口一致的对象,则此对象也可以被用于初始化bytearray.
- s = "12dffgggggh"
- print(bytearray(s, encoding="utf-8"))
- bytearray(b'12dffgggggh')
- zip([iterable, ...]) 矩阵
- name = ['alex','eric']
- age = [,]
- result = zip(name,age)
- for i in result:
- print(i)
- #执行结果
- ('alex', )
- ('eric', )
五、IO操作
- open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):
打开文件
参数filename:文件名称。
参数mode:'r'(读)、'w'(写)、'a'(追加)。
- # 只读
- f = open("log", "r")
- # 只写模式(不可读:文件不存在则创建;存在则清空内容)
- f = open("log", "w")
- # 只写模式(不可读,文件不存在则创建,存在则报错)
- f = open("log", "x")
- # 追加模式(不存在则创建;存在则只追加内容)
- f = open("log", "s")
- input([prompt]) 获取用户输入
- inp = input("请输入图书编号")
- print 打印函数
- print("请输入图书编号")
六、其他
dir 用于按模块名搜索模块定义,它返回一个字符串类型的存储列表
['__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']
- help 调用内置函数的帮助系统
- >>> help(list)
- Help on class list in module builtins:
- class list(object)
- | list() -> new empty list
- | list(iterable) -> new list initialized from iterable's items
...
...
...
[Python笔记]第四篇:内置函数的更多相关文章
- Python笔记(二十一)_内置函数、内置方法
内置函数 issubclass(class1,class2) 判断class1类是否为class2类的子类,返回True和False 注意1:类会被认为是自身的子类 >>>issub ...
- python基础12_匿名_内置函数
一个二分查找的示例: # 二分查找 示例 data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35, 36, ...
- 【python】dir(__builtins__)查看python中所用BIF(内置函数)
dir(__builtins__)查看python中所用BIF(内置函数)
- 查看python内部模块命令,内置函数,查看python已经安装的模块命令
查看python内部模块命令,内置函数,查看python已经安装的模块命令 可以用dir(modules) 或者用 pip list或者用 help('modules') 或者用 python -m ...
- Python学习(八) —— 内置函数和匿名函数
一.递归函数 定义:在一个函数里调用这个函数本身 递归的最大深度:997 def func(n): print(n) n += 1 func(n) func(1) 测试递归最大深度 import sy ...
- python之路:进阶篇 内置函数
li = [11, 22, 33] news = map( li = [100, 2200, 3300] news = map( [13, 24, 35] [11, 11, 11] [22, 4 ...
- 学习Python函数笔记之二(内置函数)
---恢复内容开始--- 1.内置函数:取绝对值函数abs() 2.内置函数:取最大值max(),取最小值min() 3.内置函数:len()是获取序列的长度 4.内置函数:divmod(x,y),返 ...
- python学习笔记(五)— 内置函数
我们常用的‘’int,str,dict,input,print,type,len‘’都属于内置函数 print(all([1,2,3,4]))#判断可迭代的对象里面的值是否都为真 print(any( ...
- python 07篇 内置函数和匿名函数
一.内置函数 # 下面这些要掌握 # len type id print input open # round min max filter map zip exec eval print(all([ ...
随机推荐
- 使用MyEclipse实现简单的Servlet程序
1. 创建一个继承于GenericServlet的类 3. 重写Server方法 package cn.school; import java.io.IOException; import javax ...
- Mac OS X 程序员利器 – Homebrew安装与使用
Mac OS X 程序员利器 – Homebrew安装与使用 Homebrew安装与使用 什么是Homebrew? Homebrew is the easiest and most flexible ...
- Y2错题解析
数据流程图描述信息的来龙去脉和实际流程,反映信息在系统中流动.处理和存储的情况.程序结构图用来描述程序结构,一般由构成系统的要素和表达要素间关系的连线或箭头构成.因果图是一种发现问题"根本原 ...
- AFNetworking (3.1.0) 源码解析 <六>
这次继续介绍文件夹Serialization下的类AFURLResponseSerialization.这次介绍就不拆分了,整体来看一下.h和.m文件. 协议AFURLResponseSerializ ...
- eclipse设置系统字体
1. 打开eclipse-->Window-->Preferences-->General-->appearance-->Colors and Fonts, 点开后选择B ...
- [PWA] 10. Trigger a version update
When the refersh button is clicked, we need to tell the waiting service worker to replace the curren ...
- LeetCode:Permutations(求全排列)
Given a collection of numbers, return all possible permutations. For example,[1,2,3] have the follow ...
- Python下载漫画
上午起来提不起劲,于是就用电脑看漫画,但是在线看漫画好烦,就想下下来看.一个一个点太麻烦,于是花了点时间用python写了个demo,把爱漫画的漫画下载下来,这样就可以随时随地看了.这也是我首次尝试用 ...
- Python 代码实现模糊查询
Python 代码实现模糊查询 1.导语: 模糊匹配可以算是现代编辑器(如 Eclipse 等各种 IDE)的一个必备特性了,它所做的就是根据用户输入的部分内容,猜测用户想要的文件名,并提供一个推荐列 ...
- codevs2034 01串2
/* 一开始认为是个水题 直接模拟 没想到只得了50分 一看数据吓niao了 模拟妥妥的TLE 实在不好优化了0.0(最快O(m)) 然后借鉴别人的 DP+神奇的输出 DP:状态:f[i][j] 前i ...