python学习笔记11-python内置函数
一、查看python的函数介绍:
https://docs.python.org/2/library/
二、python内置函数
1、abs获取绝对值:
通过python官网查看abs
abs
(x)Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument is a complex number, its magnitude is returned.
通过help查看abs
In [20]: help(abs)
Help on built-in function abs in module __builtin__:
abs(...)
abs(number) -> number #返回一个number
Return the absolute value ofthe argument. #返回绝对值
(END)
abs实例:
In [14]: def fun(x):
...: if x < 0:
...: return -x
...: return x
...:
In [15]: fun(10)
Out[15]: 10
In [16]: fun(-10)
Out[16]: 10
In [17]: abs(-10)
Out[17]: 10
In [18]: abs(10)
Out[18]: 10
In [19]: abs(-100)
Out[19]: 100
2、max()min()列表的最大值和最小值
In [22]: max([1,2,3,4,5])
Out[22]: 5
In [23]: min([1,2,3,4,5])
Out[23]: 1
Help on built-in function max in module __builtin__:
max(...)
max(iterable[, key=func]) -> value #可迭代的对象
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item.#返回最大的参数
With two or more arguments, return the largest argument.
In [26]: max('hsdhsjd','5687','12') #最长的一个
Out[26]: 'hsdhsjd'
3、获取长度len()
In [27]: s='1234'
In [28]: len(s) #取字符创的长度
Out[28]: 4
help(len)
Help on built-in function len in module __builtin__:
len(...)
len(object) -> integer #处理对象,返回整数
Return the number of items of a sequence or collection.
In [31]: len([1,2])#取列表的元素个数,2个
Out[31]: 2
In [30]: len(('a',)) #取元祖的元素个数,1个
Out[30]: 1
In [32]: len({'a':3,'d':4}) #len()统计字典有几对key,value
Out[32]: 2
4、商和余数divmod()
In [35]: help(divmod)
divmod(...)
divmod(x, y) -> (quotient, remainder)
Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.
(END)
In [36]: divmod(5,2)
Out[36]: (2, 1) #商和余数
5、pow()次方&取余
In [37]: help(pow)
Help on built-in function pow in module __builtin__:
pow(...)
pow(x, y[, z]) -> number
With two arguments, equivalent to x**y. With three arguments,
equivalent to (x**y) % z, but may be more efficient (e.g. for longs).
(END)
In [38]: pow(2,3) #两个参数,结果是x的y次方
Out[38]: 8
In [40]: pow(2,3,3) #三个参数,结果是x的y次方之后,2^3=8,8%3=2,再取个余结果是2,也就是取模
Out[40]: 2
In [39]: pow(2,3,4)
Out[39]: 0
6、round()
第一步把数字变为浮点数,
第二步,没有第二参数,把一个数字四舍五入,默认保留一位小数点.0 ,有第二个参数,第二个参数是保留几位小数
In [41]: help(round)
Help on built-in function round in module __builtin__:
round(...)
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number. Precision may be negative.
(END)
In [53]: print round(12.145) #默认是
12.0
In [15]: round(12.145,1)
Out[15]: 12.1
In [14]: round(12.145,2)
Out[14]: 12.14
In [54]: print round(12.145,3)
12.145
In [55]: print round(12.145,4)
12.145
7、callable()对象是否可调用的?
In [63]: help(callable)
Help on built-in function callable in module __builtin__:
callable(...)
callable(object) -> bool #返回一个bool值
Return whether the object is callable (i.e., some kind of function).
Note that classes are callable, as are instances with a __call__() method.
In [64]: a = 123
In [65]: callable(a) #字符a不可调用
Out[65]: False
In [66]: def b():
...: pass
...:
In [67]: callable(b)#函数b可调用
Out[67]: True
In [69]: class A(object): #定义了一个对象也是可调用的,返回true
...: pass
...:
In [70]: callable(A)
Out[70]: True
8、type()确定类型
In [66]: def b():
...: pass
In [73]: print type(b) #b为function函数类型
<type 'function'>
In [64]: a = 123
In [74]: print type(a) #a是int×××
<type 'int'>
In [75]: print type([])
<type 'list'>
9、isinstance(a,int)判断是不是指定类型,是的话返回True,不是的话,返回False
In [19]: isinstance(a,int)
Out[19]: True
In [25]: l = [1,32]
In [28]: if type(l) == type([]):
...: print 'ok'
...:
ok
In [29]: isinstance(l,list)
Out[29]: True
In [30]: isinstance(l,tuple)
Out[30]: False
In [36]: isinstance(l,(list,tuple,str)) #l是list或者tuple或者str吗?是的,就返回True
Out[36]: True
10、cmp()比较数字或者字符串的大小
In [55]: cmp(2,5)
Out[55]: -1
In [56]: cmp(2,2)
Out[56]: 0
In [57]: cmp(2,1)
Out[57]: 1
In [61]: cmp('hello','hello') #字符串相同,返回0
Out[61]: 0
In [63]: cmp('zello','hello')#首字母,z>h的ASCII值,所以,返回1
Out[63]: 1
In [62]: cmp('hello,world','hello')#逗号,的ASCII值大于null=0,返回1,
Out[62]: 1
In [65]: cmp('aellohello','hello')#ASCII值a<h,返回-1
Out[65]: -1
11、range和xrange()
In [75]: a=range(10) #直接分配内存,消耗资源
In [76]: a
Out[76]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [77]: b=xrange(10)
In [78]: b
Out[78]: xrange(10) #在循环遍历的时候再分配资源,节约资源
In [79]: for i in b:print i
0
1
2
3
4
5
6
7
8
9
二、python类型转换
1、int()转换为×××,如果转换字符串,必须全是数字,不能包括其他非数字字符
In [123]: int(0x12)
Out[123]: 18
In [1]: int('54')
Out[1]: 54
In [124]: int('0x12') #错,字符串包含了非数字x,只能是‘12’才能转为int 12
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-124-d8b06269903d> in <module>()
----> 1 int('0x12')
ValueError: invalid literal for int() with base 10: '0x12'
In [85]: int('12.479')#错,字符串包含了非数字 '.',只能是‘12479’才能转为int 12479,
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-85-4191248f183f> in <module>()
----> 1 int('12.479')
ValueError: invalid literal for int() with base 10: '12.479'
2、long()转换为长×××,与int类似用法,转换字符串不能包括非数字的字符
In [87]: long(12.4)
Out[87]: 12L
In [88]: long(12.5678)
Out[88]: 12L
In [89]: long('12')
Out[89]: 12L
In [90]: long('12.4')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-90-5122883443e4> in <module>()
----> 1 long('12.4')
ValueError: invalid literal for long() with base 10: '12.4'
3、hex()转换为16进制
hex(...)
hex(number) -> string #返回16进制的字符串,参数是int或者长×××Long int
Return the hexadecimal representation of an integer or long integer.
In [117]: hex(12)
Out[117]: '0xc'
4、float()转换为float类型
In [98]: float('123')
Out[98]: 123.0
In [99]: float(123)
Out[99]: 123.0
5、转换为复数类型
In [100]: complex(123)
Out[100]: (123+0j)
6、str(),转换为string字符串类型
In [104]: str(123)
Out[104]: '123'
In [105]: str('123')
Out[105]: '123'
In [106]: str([1,2])
Out[106]: '[1, 2]'
In [107]: str({'1':1})
Out[107]: "{'1': 1}"
In [108]: str((1,[2,3]))
Out[108]: '(1, [2, 3])'
7、list()转换为列表
class list(object)
| list() -> new empty list #参数为空,返回空列表
| list(iterable) -> new list initialized from iterable's items#参数是可迭代对象,返回迭代元素的新列表
In [110]: list('123') 参数是可迭代对象,返回迭代元素的新列表
Out[110]: ['1', '2', '3']
In [111]: list()#参数为空,返回空列表
Out[111]: []
In [112]: list((3,4,[56]))
Out[112]: [3, 4, [56]]
In [113]: list((3,4,[5,6]))#把元祖变为列表
Out[113]: [3, 4, [5, 6]]
8、tuple()转换为元祖
In [114]: tuple([3, 4, [5, 6]])#把列表变为元祖
Out[114]: (3, 4, [5, 6])
9、eval()就是字符串去字符化,删除引号,把字符串当成有效的表达式求值
In [127]: eval('0xa')
Out[127]: 10
In [2]: type(eval('0xa'))#注意转换后类型是int
Out[2]: int
In [129]: eval("['a','b',1]")
Out[129]: ['a', 'b', 1]
10、oct()转换为8进制
In [131]: oct(10)
Out[131]: '012'
11、chr()返回ASCII值0-255对应的字符
In [148]: chr(65)
Out[148]: 'A'
12、ord()返回字符的ASCII值
In [143]: ord('a')
Out[143]: 97
In [144]: ord('A')
Out[144]: 65
三、字符串处理函数
1、str.capitalizw()
In [159]: s='hello,world'
In [160]: help(s.capitalize)
capitalize(...)
S.capitalize() -> string #返回字符串,首字母大写
Return a copy of the string S with only its first character
capitalized.
In [161]: s.capitalize()
Out[161]: 'Hello,world' #H已经变为大写
2、str.replace()
replace(...)
S.replace(old, new[, count]) -> string #用新字符串替换旧字符串,count定义替换几次
Return a copy of string S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
In [172]: s.replace('h','H') #用H替换所有h
Out[172]: 'Hello,world,H'
In [169]: s.replace('h','H',1)#用H替换所有h,如果为1,只替换第一次出现的h
Out[169]: 'Hello,world,h'
In [170]: s.replace('h','H',2)#用H替换所有h,如果为2,只替换前2次出现的h
Out[170]: 'Hello,world,H'
3、str.split()
split(...)
S.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string S, using sep as the
delimiter string. If maxsplit is given, at most maxsplit
splits are done. If sep is not specified or is None, any
whitespace string is a separator and empty strings are removed
from the result.
In [176]: s1='abc'
In [177]: s1.split()
Out[177]: ['abc']
In [174]: s = 'hello a\tb\nc'
In [175]: s.split() #默认空格、tab、enter换行都会作为分隔符切分字符串
Out[175]: ['hello', 'a', 'b', 'c']
#分别以换行\n,空格' ',tab为分割符切换字符串
In [180]: s.split('\n')
Out[180]: ['hello a\tb', 'c']
In [181]: s.split(' ')
Out[181]: ['hello', '', 'a\tb\nc']
In [182]: s.split('\t')
Out[182]: ['hello a', 'b\nc']
In [183]: ip = '192.168.1.1'
In [185]: ip.split('.')
Out[185]: ['192', '168', '1', '1']
In [186]: ip.split('.',2)
Out[186]: ['192', '168', '1.1']
In [187]: ip.split('.',1)
Out[187]: ['192', '168.1.1']
4、str.join()
In [188]: help(str.join)
join(...)
S.join(iterable) -> string#参数是可迭代的对象,返回的是字符串
Return a string which is the concatenation of the strings in the
iterable. The separator between elements is S.
In [189]: s1='abc'
In [190]: s1.join('12') #在1,2之间使用abc去连接
Out[190]: '1abc2'
In [191]: s1.join('123')#在1,2,3之间用abc去连接
Out[191]: '1abc2abc3'
In [194]: ''.join(str(i) for i in range(10))#把列表的每个元素通过列表重写变为字符串
Out[194]: '0123456789'
In [195]: ' '.join(str(i) for i in range(10))
Out[195]: '0 1 2 3 4 5 6 7 8 9'
In [197]: int(''.join(str(i) for i in range(10)))
Out[197]: 123456789
5、string模块
In [198]: import string
In [199]: string.upper('abc')
Out[199]: 'ABC'
In [200]: string.lowercase
Out[200]: 'abcdefghijklmnopqrstuvwxyz'
In [201]: string.uppercase
Out[201]: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
In [202]: help(string.capitalize)
In [203]: string.capitalize('hello')
Out[203]: 'Hello'
In [204]: help(string.replace)
In [205]: string.replace('hello','o','O')
Out[205]: 'hellO'
In [206]: s
Out[206]: 'hello a\tb\nc'
In [207]: s.replace('h','H')
Out[207]: 'Hello a\tb\nc'
三、序列处理函数
1、filter()数据过滤处理函数,例子:把range(10)通过函数f处理,偶数显示在列表中,function = None,不处理直接返回原来的列表
filter(...)
filter(function or None, sequence(序列)) -> list, tuple, or string#序列的元素都会被函数处理
Return those items of sequence for which function(item) is true. If
function is None, return the items that are true. If sequence is a tuple
or string, return the same type, else return a list
In [275]: filter(None,range(10)) #function是None,不处理直接返回range(10)
Out[275]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
In [271]: def f(x):
...: if x %2 == 0:
...: return True
...:
In [273]: filter(f,range(10)) #把range(10)通过函数f处理,偶数显示在列表中
Out[273]: [0, 2, 4, 6, 8]
#filter使用匿名函数lambda
In [303]: filter(lambda x: x%2==0,range(10))#表示,lambda x成立的条件是:x%2==0并且x属于range(10)
Out[303]: [0, 2, 4, 6, 8]
2、zip()对多个序列处理,合并成一个大的序列
zip(...)
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.#最小的参数
In [277]: l1 = [1,2,3]
In [278]: l2 = ['a','b','c']
In [279]: zip(l1,l2)
Out[279]: [(1, 'a'), (2, 'b'), (3, 'c')]
In [280]: dict(zip(l1,l2))
Out[280]: {1: 'a', 2: 'b', 3: 'c'}
In [284]: l3 = ['I','II']#l3的长度少一个,结果也会少一个
In [285]: zip(l1,l2,l3)
Out[285]: [(1, 'a', 'I'), (2, 'b', 'II')]
3、map()返回列表,通过函数对序列相应的元素进行处理,如果需要处理一个序列,对应函数的参数是一个,如果需要处理的是两个序列,对应函数的桉树是三个,以此类推。
map(...)
map(function, sequence[, sequence, ...]) -> list
Return a list of the results of applying the function to the items of
the argument sequence(s). If more than one sequence is given, the
function is called with an argument list consisting of the corresponding
item of each sequence, substituting None for missing values when not all
sequences have the same length. If the function is None, return a list of
the items of the sequence (or a list of tuples if more than one sequence).
In [287]: map(None,l1,l2,l3)
Out[287]: [(1, 'a', 'I'), (2, 'b', 'II'), (3, 'c', None)]
In [288]: def f(x):
...: return x**2
...:
In [289]: map(f,l1) #通过函数f对l1的每个参数处理,一个序列,对应函数的一个参数
Out[289]: [1, 4, 9]
In [294]: l1
Out[294]: [1, 2, 3]
In [290]: l2=[4,5,6]
In [292]: def f(x,y): #定义函数,返回乘积,两个序列,对应函数的两个参数
...: return x*y
...:
In [293]: map(f,l1,l2) #给了两个序列,则这两个序列都会被函数f处理,并返回结果
Out[293]: [4, 10, 18]
注意:如果需要处理的是三个序列,对应函数的三个参数,以此类推。
#map使用匿名函数lambda
In [304]: map(lambda x,y: x*y,range(10),range(10))
Out[304]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
4、reduce() 返回值value, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5)
In [295]: help(reduce)
reduce(...)
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
In [296]: def f(x,y):
...: return x+y
...:
In [297]: reduce(f,range(1,101))
Out[297]: 5050
#reduce使用匿名函数lambda
In [300]: reduce(lambda x,y:x+y,[1,2,3,4,5])
Out[300]: 15
5、列表表达式(列表重写)
In [305]: [i for i in range(10)]
Out[305]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [306]: [i*2 for i in range(10)]
Out[306]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
In [307]: [i**2 for i in range(10)]
Out[307]: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
In [308]: [i for i in range(10) if i %3==0]
Out[308]: [0, 3, 6, 9]
In [309]: [i*2 for i in range(10) if i %3==0]
Out[309]: [0, 6, 12, 18]
In [310]: [i*2+10 for i in range(10) if i %3==0]
Out[310]: [10, 16, 22, 28]