lambda表达式
定义函数(普通方式)
def f1():
return 123 f2 = lambda : 123 def f3(a1,a2):
return a1+a2 定义函数(lambda表达式)
f4 = lambda a1,a2: a1+a2 示例:
def f1(x):
if x % 2 ==1:
return x + 100
else:
return x ret = map(lambda x: x + 100 if x % 2 ==1 else x, [1,2,3,4])
# print(ret)
for i in ret:
print(i)
运算结果:
101
2
103
4
内置函数
1,abs()
绝对值
参数可以是:负数、正数、浮点数或者长整形
i = abs(-123) #绝对值
print(i) i = abs(-1.2)
print(i) i = abs(1.2)
print(i) i = abs(-11216.5)
print(i) i = abs(11216.5)
print(i) 运算结果:
123
1.2
1.2
11216.5
11216.5
2,all ()
循环参数
如果每个元素都为真,那么all的返回值为真
假: 0,None,"",[],(),{}, ==> 总结出;0,None,空值 为假
示例:
all(['a', 'b', 'c', 'd']) #列表list,元素都不为空或0
True
all(['a', 'b', '', 'd']) #列表list,存在一个为空的元素
False
all([0, 1,2, 3]) #列表list,存在一个为0的元素
False all(('a', 'b', 'c', 'd')) #元组tuple,元素都不为空或0
True
all(('a', 'b', '', 'd')) #元组tuple,存在一个为空的元素
False
all((0,1,2,3,4)) #元组tuple,存在一个为0的元素
False
all([]) # 空列表
True
all(()) # 空元组
True
3,any()
只有有一个真,则为真
def any(iterable):
for i in iterable:
if i:
return False
return True
示例:
any(['a', 'b', 'c', 'd']) #列表list,元素都不为空或0
True any(['a', 'b', '', 'd']) #列表list,存在一个为空的元素
True any([0, '', False]) #列表list,元素全为0,'',false
False any(('a', 'b', 'c', 'd')) #元组tuple,元素都不为空或0
True any(('a', 'b', '', 'd')) #元组tuple,存在一个为空的元素
True any((0, '', False)) #元组tuple,元素全为0,'',false
False any([]) # 空列表
False any(()) # 空元组
False
4,divmod(a,b)函数
divmod(a,b)方法返回的是a//b(除法取整)以及a对b的余数
li = divmod(10,3)
print(li)
运算结果:
(3, 1)
5,eval()
可以执行一个字符串形式的表达式;简单的表达式,可以给算出来
ret = eval("122+45+53")
print(ret)
运算结果:
220 ret = eval("a + 60",{"a":99})
print(ret)
运算结果:
159
6,exec()
可以执行py代码 ;不会返回值,直接输出结果
exec("print(\"hello, world\")")
运算结果:
hello, world
7,filter()
对于序列中的元素进行筛选,最终获取符合条件的序列(需要循环)
(函数,可迭代的对象) 过滤器
示例:
法一:
def f1(x):
if x >22:
return True
else:
return False ret = filter(f1,[11,22,33,44])
for i in ret:
print(i)
法二:
def f1(x):
return x > 22
ret = filter(lambda x: x > 22, [11,22,33,44])
for i in ret:
print(i)
运算结果:
33
44
8,map()
(函数,可以迭代的对象,让元素统一操作)
示例:
def f(x):
return x * x r = map(f, [1, 2, 3, 4, 5, 6])
list(r)
[1, 4, 9, 16, 25, 36]
****************
def f1(x):
if x % 2 ==1:
return x + 100
else:
return x ret = map(lambda x: x + 100 if x % 2 ==1 else x, [1,2,3,4])
# print(ret)
for i in ret:
print(i)
9,globals()
获取全局变量 globals()对象的值能修改
def f1():
name = 123
print(globals(name))
10,locals()
获取局部变量 locals()对象的值不能修改
def f1():
name = 123 print(locals(name))
11,isinstance()
判断对象是否存在某个类创建的
a = 10 def b():
pass print (isinstance(a,(int,str)))
print (isinstance(a,(float,str)))
print (isinstance(b,(str,int))) class c:
pass obj = c() print (isinstance(obj,(c,int))) 运算结果:
True
False
False
True
12,__repr__
ascii对象的类中找 __repr__,获取其返回值
class Foo:
def __repr__(self):
return "hello" obj = Foo()
r = ascii(obj)
print(r)
运算结果:
hello
13,iter()
迭代方法,依次取值
obj = iter([11,22,33,44])
print(obj)
r1 = next(obj) #next,取下一个值,一个变量里的值可以一直往下取,直到没有就报错
print(r1) r2 = next(obj)
print(r2)
r3 = next(obj)
print(r3)
运算结果:
11
22
33
14,max()
取最大值
li = ([11,22,33,44,1])
r = max(li)
print(r)
运算结果:
44
15,min()
取最小值
li = ([11,22,33,44,1])
r = min(li)
print(r)
运算结果:
1
16,pow(x,y)
求次方
i = pow(2,10)
print(i)
运算结果:
1024
17,sum()
求和
r = sum([11,22,33,44])
print(r)
运算结果:
110
18,round 四舍五入
ret = round(4.8)
print(ret)
19,zip()
zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表
a = [1,2,3]
b = [4,5,6] r = zip(a,b) # zip,让a,b值1 1对应
for i in r: print(i)
运算结果:
(1, 4)
(2, 5)
(3, 6)
20,import()
导入
import math #入导math模块
math.floor() #调用math模块中的floor()函数 python from使用方法例如:
from math import floor #导入math模块中的floor函数方法
floor() #调用floor()函数方法
21,sort()
排序
li = [11,33,55,22,55,]
print(li)
li.sort()
print(li)
运算结果:
[11, 33, 55, 22, 55]
[11, 22, 33, 55, 55]
22,flush()
刷新内部缓冲区
示例:
f = open("foo.txt", "wb")
print ("Name of the file:hello word "), f.name f.flush() f.close()
运算结果:
Name of the file:hello word
23,read()
读取文件内容 (给read加上一个参数,指定要读取的最大行数)
示例:
f = open("a_f.dat","rb")
data = f.read(10000)
f.close()
24,readline()
readline判断文件读取结束的方法
示例:
filename = raw_input('Enter your file name') #输入要遍历读取的文件路径及文件名
file = open(filename,'r')
done = 0
while not done:
aLine = file.readline()
if(aLine != ''):
print aLine,
else:
done = 1
file.close() #关闭文件
25,hash
hash对key的优化,相当于给输出一种哈希值
li = "sdglgmdgongoaerngonaeorgnienrg"
print(hash(li))
26,callable
callable表示一个对象是否可执行
def f1(): #看这个函数能不能执行,能发挥True return 123 f1() r = callable(f1) print(r)
进制
r = bin(11) #二进制
print(r) r = oct(8) #八进制
print(r) i = int(10) #十进制
print(i) r = hex(14) #十六进制
print(r) 运算结果:
0b1011
0o10
10
0xe
进制转换
示例:
int(10)
i = int('0b11',base=2) #二进制转换十进制
print(i) i = int('0o11',base=8) #八进制转换十进制
print(i) i = int('0xe',base=16) #十六进制转换十进制
print(i) 运算结果:
3
9
14
字节,字符串
示例:
#bytes("xxxx",encoding="utf-8") i = bytes("你好,世界",encoding="utf-8")
print(i) 运算结果:
b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x8c\xe4\xb8\x96\xe7\x95\x8c'
chr() 数字转换成字符 # 只适用在ascii中
示例:
c = chr(253)
print(c)
运算结果:
y
ord() 字符转换成数字# 只适用在ascii中
示例:
c = ord('x')
print(c)
运算结果:
120
随机数:
import random print (random.random())
print (random.randint(1,2))
print (random.randrange(1,10))
随机验证码:
import random
temp = ""
for i in range(6):
#生成 0—4的随机数
num = random.randrange(0,4)
# 如果随机数是1 或 3,那么就在验证码中生成一个 0—9的随机数字
#否则,验证码中生成一个随机字母
if num == 3 or num== 1:
rad2 = random.randrange(0,10)
temp = temp + str(rad2)
else:
rad1 = random.randrange(65,91)
c1 = chr(rad1)
temp = temp + c1
print(temp)
文件操作
一,打开文件
二,操作文件
三,关闭文件
open (文件名,模式,编码)
格式:
f =open("文件名","r") # r 只读模式 data = f.read() f.close() peint(data)
打开文件的模式:
普通方式(python内部自动转换)
1)只读模式,r
f = open("ha.log","r")
f.write("kdjaskjskasdksjdaksj")
f.close
2)只写模式,w 【不可读,文件不存在则创建;存在则清空文件内容再写入】
f = open("ha1.log","w")
f.write("sdhjf43dk3rfk")
f.close()
3)只写模式,x 【不可读;文件不存在则创建;文件存在则报错】
f = open("ha2.log","w")
f.write("dahhadiu3528")
f.close()
4)追加模式【不可读;不存在的则创建;存在则追加到末尾】
f = open("ha2.log","a")
f.write("666jjjksk")
f.close()
以字节的方式(二进制的方式)“b”
1)只读模式,rb 【文件不存在则创建;文件存在则清空内容】
f = open("ha.log","rb")
data = f.read()
f.close()
print(data)
str_data = str(data, encoding="utf-8")
print(str_data)
2)只读模式,wb 【文件不存在则创建;存在则清空内容】
f = open("ha.log","wb")
str_data = "中国人"
bytes_data = bytes(str_data, encoding="utf-8")
f.write(bytes_data)
f.close()
同时读写文件 “+”
1)r+ 开始向后读,写时追加,指针调到最后
2)w+,先清空,再写,才可以读。写,指针到最后
3)x+如果文件存在则报错
4)a+,打开的同时指针已经移到最后,追加在最后
f.tell()#获取指针的位置
f.seek(num) #调整指针位置
f.write("")#写入
f.read("") # 读取
操作
class file(object)
def close(self): # real signature unknown; restored from __doc__
关闭文件
"""
close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing.
""" def fileno(self): # real signature unknown; restored from __doc__
文件描述符
"""
fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read().
"""
return 0 def flush(self): # real signature unknown; restored from __doc__
刷新文件内部缓冲区
""" flush() -> None. Flush the internal I/O buffer. """
pass def isatty(self): # real signature unknown; restored from __doc__
判断文件是否是同意tty设备
""" isatty() -> true or false. True if the file is connected to a tty device. """
return False def next(self): # real signature unknown; restored from __doc__
获取下一行数据,不存在,则报错
""" x.next() -> the next value, or raise StopIteration """
pass def read(self, size=None): # real signature unknown; restored from __doc__
读取指定字节数据
"""
read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.
"""
pass def readinto(self): # real signature unknown; restored from __doc__
读取到缓冲区,不要用,将被遗弃
""" readinto() -> Undocumented. Don't use this; it may go away. """
pass def readline(self, size=None): # real signature unknown; restored from __doc__
仅读取一行数据
"""
readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.
"""
pass def readlines(self, size=None): # real signature unknown; restored from __doc__
读取所有数据,并根据换行保存值列表
"""
readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.
"""
return [] def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
指定文件中指针位置
"""
seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to
(offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file). If the file is opened in text mode,
only offsets returned by tell() are legal. Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable.
"""
pass def tell(self): # real signature unknown; restored from __doc__
获取当前指针位置
""" tell() -> current file position, an integer (may be a long integer). """
pass def truncate(self, size=None): # real signature unknown; restored from __doc__
截断数据,仅保留指定之前数据
"""
truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell().
"""
pass def write(self, p_str): # real signature unknown; restored from __doc__
写内容
"""
write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
"""
pass def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
将一个字符串列表写入文件
"""
writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string.
"""
pass def xreadlines(self): # real signature unknown; restored from __doc__
可用于逐行读取文件,非全部
"""
xreadlines() -> returns self. For backward compatibility. File objects now include the performance
optimizations previously implemented in the xreadlines module.
"""
pass 2.x
2.x
class TextIOWrapper(_TextIOBase):
"""
Character and line based layer over a BufferedIOBase object, buffer. encoding gives the name of the encoding that the stream will be
decoded or encoded with. It defaults to locale.getpreferredencoding(False). errors determines the strictness of encoding and decoding (see
help(codecs.Codec) or the documentation for codecs.register) and
defaults to "strict". newline controls how line endings are handled. It can be None, '',
'\n', '\r', and '\r\n'. It works as follows: * On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '' or '\n', no translation takes place. If newline is any
of the other legal values, any '\n' characters written are translated
to the given string. If line_buffering is True, a call to flush is implied when a call to
write contains a newline character.
"""
def close(self, *args, **kwargs): # real signature unknown
关闭文件
pass def fileno(self, *args, **kwargs): # real signature unknown
文件描述符
pass def flush(self, *args, **kwargs): # real signature unknown
刷新文件内部缓冲区
pass def isatty(self, *args, **kwargs): # real signature unknown
判断文件是否是同意tty设备
pass def read(self, *args, **kwargs): # real signature unknown
读取指定字节数据
pass def readable(self, *args, **kwargs): # real signature unknown
是否可读
pass def readline(self, *args, **kwargs): # real signature unknown
仅读取一行数据
pass def seek(self, *args, **kwargs): # real signature unknown
指定文件中指针位置
pass def seekable(self, *args, **kwargs): # real signature unknown
指针是否可操作
pass def tell(self, *args, **kwargs): # real signature unknown
获取指针位置
pass def truncate(self, *args, **kwargs): # real signature unknown
截断数据,仅保留指定之前数据
pass def writable(self, *args, **kwargs): # real signature unknown
是否可写
pass def write(self, *args, **kwargs): # real signature unknown
写内容
pass def __getstate__(self, *args, **kwargs): # real signature unknown
pass def __init__(self, *args, **kwargs): # real signature unknown
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 3.x
3.x
关闭文件
with open ("ha.log","r") as f :
f.read()
同时打开两个文件(2.7以上版本)
with open('log1','r') as obj1, open('log2', 'r') as obj2:
pass with open('源文件','r') as obj1, open('新文件', 'w') as obj2:
for line in obj1:
obj2.write(line)
详细请参考:http://www.cnblogs.com/wupeiqi/articles/4943406.html
http://www.cnblogs.com/wupeiqi/articles/4911365.html