python学习笔记11-python内置函数

一、查看python的函数介绍:

二、python内置函数

1、abs获取绝对值:

通过python官网查看absabs(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

...:         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函数类型

In [64]: a = 123

In [74]: print type(a) #a是int×××

In [75]: print type([])

9、isinstance(a,int)判断是不是指定类型,是的话返回True,不是的话,返回FalseIn [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

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)

in ()

----> 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)

in ()

----> 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)

in ()

----> 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]

python 内置函数转list_python学习笔记11-python内置函数相关推荐

  1. python编程语言继承_python应用:学习笔记(Python继承)

    学习笔记(Python继承)Python是一种解释型脚本语言,可以应用于以下领域: web 和 Internet开发 科学计算和统计 人工智能 教育 桌面界面开发 后端开发 网络爬虫 有几种叫法(父类 ...

  2. 凸优化学习笔记 11:对偶原理 拉格朗日函数

    前面讲了凸优化问题的定义,以及一些常见的凸优化问题类型,这一章就要引入著名的拉格朗日函数和对偶问题了.通过对偶问题,我们可以将一些非凸问题转化为凸优化问题,还可以求出原问题的非平凡下界,这对复杂优化问 ...

  3. python内建函数测试对象身份_Python学习笔记 03 Python对象

    1.Python对象 Python对象都拥有三个特性:身份.类型和值. 身份:每一个对象都有一个唯一的身份标识自己,任何对象的身份都可以使用内建函数id()来得到.这个值可以被认为是该对象的内存地址. ...

  4. 学习笔记(11):Python网络编程并发编程-粘包底层原理分析

    立即学习:https://edu.csdn.net/course/play/24458/296241?utm_source=blogtoedu  1.send和recv底层分析 1)不管是recv还是 ...

  5. python绘制三维地形_【学习笔记】Python科学计算三维可视化(黄天羽、嵩天)(学习中。。)|python基础教程|python入门|python教程...

    0 导学 目的:掌握利用三维效果表达科学和工程数据的能力 传播一种思想:可视化技术是数据之眼 内容组织: 流体数据的标量可视化.矢量可视化实例 三维扫描数据(模型/地形)可视化实例 三维地球场景可视化 ...

  6. python while循环例题_【学习笔记】python:5for循环与while循环(上)

    点击上方蓝字,关注我吧 课 程 表 for循环代发格式 for循环的3个要点即是:1.空房间:2.一群等着办业务的人:3.业务流程 空房间的学名叫[元素](item),你可以把它当成是一个变量.那么首 ...

  7. python三维数组可视化_【学习笔记】Python科学计算三维可视化(黄天羽、嵩天)(学习中。。)...

    0 导学 目的:掌握利用三维效果表达科学和工程数据的能力 传播一种思想:可视化技术是数据之眼 内容组织: 流体数据的标量可视化.矢量可视化实例 三维扫描数据(模型/地形)可视化实例 三维地球场景可视化 ...

  8. 【printf函数与scanf函数】(学习笔记5--标准I/O函数)

    标准I/O函数 一.printf函数 二.scanf函数 一.printf函数 printf函数通常被称为"格式化打印函数",它的第一个参数称为"格式化字符串" ...

  9. find(==)函数matlab,MATLAB学习笔记(1 )find函数

    最近,需要用MATLAB处理一批数据,数据的格式如下: 如上图所示,在一个文本文件中存储着一个N行8列的矩阵,第一列的取值为-1,0,1.为了将所有含有这三个值的行分别提出出来.使用find函数应该是 ...

最新文章

  1. 学python爬虫需要什么基础-学爬虫,需要掌握哪些Python基础?
  2. Pyhton基础篇(2)-变量、用户输入及条件语句(已更新)
  3. Android与服务器端数据交互(基于SOAP协议整合android+webservice)
  4. 手机是怎么确定位置信息的?
  5. Unity字节序问题
  6. 2018.10.20 2018-2019 ICPC,NEERC,Southern Subregional Contest(Online Mirror, ACM-ICPC Rules)
  7. 2019华为软件精英挑战赛经验总结
  8. WMS软件哪个好?排名怎样
  9. BabeLua常见问题
  10. kindle导出电子书pc_在PC版Kindle上阅读Mobi电子书
  11. complie myplayer on svn source code
  12. 计算机组策略怎么设置远程桌面,如何利用组策略编辑器对远程桌面进行管理
  13. android 4.4 沉浸模式,大杀器:安卓4.4沉浸模式强制开启!
  14. [WUSTCTF2020]alison_likes_jojo
  15. 苹果考虑推迟发布5G iPhone
  16. Windows本地下载远程服务器文件方法总结
  17. 重定向与转发的使用和区别
  18. Thymeleaf 表单回填
  19. 通过左旋和右旋来实现搜索二叉树的自平衡
  20. redis:redis介绍和安装、普通连接和连接池、redis 5大数据类型之字符串、Hash、列表、其他操作(通用)、管道、django使用redis、接口缓存

热门文章

  1. 一些世界名著的开场白和结束语
  2. ACCP 8.0 jQuery 第八章 上机练习
  3. 《拷贝兔》通过4个字符将文件发送到另一台电脑
  4. 向iPhone或者ipad导入文件夹或者文件
  5. 蓝桥杯 BFS经典题 —— 卡片换位(单走华容道)
  6. Ansys-非线性-悬臂梁非线性屈曲分析学习收获
  7. 中钢协2007年第三次行业信息发布会新闻稿
  8. c语言调试结果显示不是内部或外部命令,telnet命令测试端口连接是否正常, telnet不是内部或外部命令的方案...
  9. Nginx获取自定义header
  10. 2018GDKOI旅行记