Python 内建函数小结
2016-07-23 16:54
661 查看
Python 3.5.1 Anaconda 4.0.0 (64-bit)
Python 内置函数
链接:https://docs.python.org/3.5/library/functions.html?highlight%EF%BC%9Dprint#hasattr
any(iterable):当iteralbe里存在元素是True时就返回True,用于判断iterable是否存在满足某个条件的元素(英文: Return True if any element of the iterable is true. If the iterable is empty, return False.)
repr(object):把object输出一个打印格式良好的(printable)字符串
eval(expression, globals=None, locals=None):参数是一个表达式expression,在当前环境(也可由globals和locals来设定)执行/计算表达式的值,一般来言,对于很多类型的变量obj,总是有obj=eval(ascii(obj))=eval(repr(obj))成立
hex(x):把x转化为十六进制格式字符串,以0x开头
oct(x):把x转化为八进制格式字符串,以0o开头
ord(c):返回c的Unicode code point,与chr正好相反
staticmethod(function):省略
getattr(object, name[, default]):得到object的属性name
setattr(object, name, value):设置object的属性name的值为value
hasattr(object, name):判断object是否有属性name
locals:省略
vars([object]):省略
issubclass(class, classinfo):判断class是否是classinfo的子类
sum(iterable[, start]):计算iterable里各元素的和
min(iterable, *[, key, default]) & min(arg1, arg2, *args[, key]):与max类似,不过是最小的元素
sorted(iterable[, key][, reverse]):按照key指定的规则对iterable里各元素排序
print
print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
Python 内置函数
链接:https://docs.python.org/3.5/library/functions.html?highlight%EF%BC%9Dprint#hasattr
abs
abs(x):返回x的绝对值,若是复数,则返回其大小In [67]: abs(complex(3, 4)) Out[67]: 5.0
all & any
all(iterable):当iterable里所有元素都是True时才返回True,用于判断iterable是否都满足某个条件 (英文: Return True if all elements of the iterable are true (or if the iterable is empty))any(iterable):当iteralbe里存在元素是True时就返回True,用于判断iterable是否存在满足某个条件的元素(英文: Return True if any element of the iterable is true. If the iterable is empty, return False.)
In [52]: s = Series([1,2,3],index=['a','b','c']) #Series是iterable类型的 In [53]: all(s>0) Out[53]: True In [54]: any(s==2) Out[54]: True In [55]: lst = [1,2,3] #list不是iterable类型的,无法成为all和any的参数 In [56]: all(lst>0) Traceback (most recent call last): File "<ipython-input-69-b85f33266c83>", line 1, in <module> all(lst>0) TypeError: unorderable types: list() > int()
ascii & repr & eval
ascii(object):把object输出一个打印格式良好的(printable)字符串,但会避开non-ascii的字符,使用 \x \u 或 \U 来表示repr(object):把object输出一个打印格式良好的(printable)字符串
eval(expression, globals=None, locals=None):参数是一个表达式expression,在当前环境(也可由globals和locals来设定)执行/计算表达式的值,一般来言,对于很多类型的变量obj,总是有obj=eval(ascii(obj))=eval(repr(obj))成立
In [73]: data Out[73]: {'a': 'A', 'b': 2, 'c': 3.0} In [74]: ascii(data) Out[74]: "{'b': 2, 'a': 'A', 'c': 3.0}" In [75]: repr(data) Out[75]: "{'b': 2, 'a': 'A', 'c': 3.0}" In [76]: ascii(data) == repr(data) Out[76]: True In [80]: data == eval(ascii(data)) Out[80]: True In [81]: data == eval(repr(data)) Out[81]: True In [82]: x = 1 In [83]: eval('x+1') Out[83]: 2 In [84]: eval('0x19') Out[84]: 25 In [85]: eval('0b1011') Out[85]: 11
bin & hex & oct
bin(x):把x转化为二进制格式字符串,以0b开头hex(x):把x转化为十六进制格式字符串,以0x开头
oct(x):把x转化为八进制格式字符串,以0o开头
In [94]: bin(4) Out[94]: '0b100' In [96]: hex(24) Out[95]: '0x18' In [96]: oct(21) Out[96]: '0o25'
class
bool & bytearray & bytes & float & frozenset & int & list & object & set & str:省略chr & ord
chr(i):返回的字符的unicode code point是iord(c):返回c的Unicode code point,与chr正好相反
In [114]: ord('a') Out[114]: 97 In [115]: chr(97) Out[115]: 'a' In [116]: chr(8364) Out[116]: '€'
classmethod & staticmethod
classmethod(function):省略staticmethod(function):省略
compile
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1):Compile the source into a code or AST object. Code objects can be executed by exec() or eval(). source can either be a normal string, a byte string, or an AST object.complex
class complex([real[, imag]]):返回复数,参数为1个或两个数字,或1个字符串In [117]: complex(2, 3) Out[117]: (2+3j) In [118]: complex('2+3j') #当是字符串时,+或-两边不能有空格 Out[118]: (2+3j)
delattr & getattr & setattr & hasattr
delattr(object, name):删除object的属性namegetattr(object, name[, default]):得到object的属性name
setattr(object, name, value):设置object的属性name的值为value
hasattr(object, name):判断object是否有属性name
dir
dir([object]):无参数时,返回当前scope里所有变量名称,有参数时,返回当前参数的所有属性和方法divmod
divmod(a, b):若两参数是整数,则返回参数之间的商和余数,即divmod(a, b)=(a//b, a%b)
In [140]: divmod(10, 3) Out[140]: (3, 1)
enumerate
enumerate(iterable, start=0):参数为一序列或者其他有next方法的iterator,返回index和valueIn [141]: st = ['Spring', 'Summer', 'Fall', 'Winter'] In [142]: list(enumerate(st)) Out[142]: [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] In [143]: list(enumerate(st, start=2)) #可以设置index计数的起始位置 Out[143]: [(2, 'Spring'), (3, 'Summer'), (4, 'Fall'), (5, 'Winter')]
exec
eval(expression, globals=None, locals=None):执行一个字符串代码或代码对象,可以通过globals或locals参数设置执行的范围filter
filter(function, iterable): (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is NoneIn [148]: func = lambda x: x>2 #准确来说,function参数更像是一个筛选条件,满足筛选条件的元素留下 In [149]: list(filter(func, [1,2,3,4])) Out[149]: [3, 4] In [150]: [item for item in [1,2,3,4] if func(item)] Out[150]: [3, 4]
format
format(value[, format_spec]):省略globals & locals & vars
globals:省略locals:省略
vars([object]):省略
hash
hash(object):返回object的hash值In [166]: hash(5) Out[166]: 5 In [167]: hash(5.0) Out[167]: 5 In [168]: hash(5.1) Out[168]: 230584300921368581
help
help([object]):返回参数的帮助文档id
id(object):返回object在内存中的地址位置input
input([prompt]):读取键盘输入并返回该输入值In [178]: name = input('Enter your name: ') Enter your name: Xiaoming In [179]: name Out[179]: 'Xiaoming'
isinstance & issubclass
isinstance(object, classinfo):判断object是否属性classinfo类issubclass(class, classinfo):判断class是否是classinfo的子类
In [181]: isinstance([1,2,3], list) Out[181]: True
iter
iter(object[, sentinel]):省略len & sum
len(s):计算s的长度sum(iterable[, start]):计算iterable里各元素的和
map
map(function, iterable, …):对iterable里每个元素执行函数functionIn [195]: func = lambda x: x+1 In [196]: list(map(func, [1,2,3])) Out[196]: [2, 3, 4]
max & min & sorted
max(iterable, *[, key, default]) & max(arg1, arg2, *args[, key]):按照key指定的规则返回iterable里最大的元素min(iterable, *[, key, default]) & min(arg1, arg2, *args[, key]):与max类似,不过是最小的元素
sorted(iterable[, key][, reverse]):按照key指定的规则对iterable里各元素排序
In [206]: max([2,3,4], key=lambda x:x%3) #返回列表里除以3的余数最大的元素 Out[206]: 2 In [208]: min([2,3,4], key=lambda x:x%3) #返回列表里除以3的余数最小的元素 Out[208]: 3 In [207]: sorted([2,3,4], key=lambda x:x%3, reverse=True) #与上面差不多,只不过是全元素排序 Out[207]: [2, 4, 3]
next
next(iterator[, default]):返回iterator下一个元素open
open(file, mode=’r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None):按照模式mode以编码encoding打开file以供读/写/执行/其他,file是文件的绝对/相对路径名(包括文件名)Character | Meaning |
---|---|
‘r’ | open for reading (default) |
‘w’ | open for writing, truncating the file first |
‘x’ | open for exclusive creation, failing if the file already exists |
‘a’ | open for writing, appending to the end of the file if it exists |
‘b’ | binary mode |
‘t’ | text mode (default) |
‘+’ | open a disk file for updating (reading and writing) |
‘U’ | universal newlines mode (deprecated) |
power
power(x, y[, z]):相同于x**yproperty
class property(fget=None, fset=None, fdel=None, doc=None):定义一个property类,有get/set/del方法range
range(start, stop[, step]):返回从start到stop,以step为间隔的数字序列reversed
reversed(seq):让seq里各元素顺序In [216]: list(reversed([1,3,2,5,4])) Out[216]: [4, 5, 2, 3, 1]
round
round(number[, ndigits]):当没有参数ndigits时,相同于四舍五入的整数;当有参数ndigits时,相当于取ndigits位小数位后四舍五入的浮点数;但注意,当小数位有5且恰好要舍弃它时,有时进位有时不进位!?In [220]: round(2.49) Out[220]: 2 In [221]: round(2.51) Out[221]: 3 In [222]: round(2.5) Out[222]: 2 In [223]: round(2.435, 2) Out[223]: 2.44 In [224]: round(2.675, 2) Out[224]: 2.67
slice
class slice(start, stop[, step]):切片类,用于从序列里切片In [230]: lst = [0,1,2,3,4,5] In [231]: lst[1:5:2] #[1:5:2]就是一个slice,表示第1,3个索引(不含第5个索引),即第2,4个元素 Out[231]: [1, 3]
super
super([type[, object-or-type]]):省略type
class type(object):返回object的类型zip
zip(*iterables):把若干iterable捆绑在一起形成一个新的iterable相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法