首页 > 技术文章 > python内置函数每个执行一次

cp-miao 2016-06-03 10:58 原文

 

 
open    #   with open('log','r') as f:    或者   r=open(filename,r+)
with open ('1.txt','r',encoding='utf-8')as r,open ('2','x',encoding='utf-8')as w:  同时操作两行。
      readline()每次读取一行,当前位置移到下一行;
      readlines()读取整个文件所有行,保存在一个列表(list)变量中,一行一个元素。
      read(size)从文件当前位置起读取size个字节(如果文件结束,就读取到文件结束为止。
      trancate   截取前面内容,删除后面内容。fileObject.truncate( [ size ])
      flush  强行刷入硬盘
      
    
split('符号')    #以符号为标准进行分割。
 
sorted    #sort()与sorted()的不同在于,sort是在原位重新排列列表,而sorted()是产生一个新的列表。
1 >>> print sorted([5, 2, 3, 1, 4])
2 [1, 2, 3, 4, 5]
3 
4 >>> L = [5, 2, 3, 1, 4]
5 >>> L.sort()
6 >>> print L
7 [1, 2, 3, 4, 5]

abs   # 返回绝对值

1 print (abs(-11))
2 11

all   #全部True  则为True

print (all([True,11,2,3]))
True

any  #只要有True 即为真

print (any([True,0,None,3]))
True

bin  #转换二进制   oct  #  八进制    int  #10进制      hex #十六进制

print (bin(2))
0b10

bool  #转换为布尔值

print (bool(None))
False

bytes  #转换为字节,也是转换为二进制

print (bytes(1))

b'\x00'

chr  #数字转ASCII字母      ord   #字母转换ASCII数字      制作验证码的时候可以用到

print (chr(99),ord('c'))    
c 99

dir   #查看该模块可以使用的方法

print (dir(open))  
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']

divmod   #取除后的余数

print (divmod(5,2))
(2, 1)

range     #返回指定的数

for i in range(5,10):print(i)
5 6 7 8 9 10
enumerate   #给值加上key
my=['q','w','e']
for i in enumerate(my):print (i)
(0, 'q')
(1, 'w')
(2, 'e')

eval   #在计算excel表格里面的数据的时候可以用上,计算简单表达式的结果。   用得比较多

print ( eval( ' a + 1 ', { 'a' : 99 } ) )
100

 exec   #可以处理比eval复杂的,没有返回值,只执行函数。          complex   #用来编译代码的

exec("for i in range(10):print (i)")

filter    #把列表传入函数里面执行,内部调用bool_func,结果为True的append, 返回结果为True的(过滤掉,只对结果为真的进行操作和放回)。

filter(lamdba x:x%2 == 0,[1,2,3,4]
[2,4]

map    #对所有的值进行迭代操作,返回结果。

map(lambda x:x*2,[11,22,33])

reduce   #对sequence中的item顺序迭代调用function,函数必须要有2个参数。要是有第3个参数,则表示初始值,可以继续调用初始值,返回一个值。

>>> reduce(lambda x,y:x*y,range(1,6),3)           #初始值3,结果再*3
360

 

float    #浮点型, 保留整数后面的小数点

globals  #取出全部的全局变量

locals    #取出全部的局部变量

isinstance    #判断变量的类型  ,同时可以判断是不是一个类,或者函数

 

isinstance([11,22,33],list)
True

 issubclass     #判断第一个值是否为第二个值的子类

class Line:
    pass
class RedLine(Line):
    pass
class Rect:
    pass

print(issubclass(RedLine,Line ))
print(issubclass(Rect, Line))

iter          #对字符进行迭代

a=iter([11,22,33])
n1=next(a)

max        #取最大值
min         #取最小值

pow         #求次方

reversed   #反转

round       #四舍五入

sum          #求和

 

 

 

 
 
 

推荐阅读