1、函数参数(引用) 函数的传参,传的是引用
def func(args):
args.appand(123)
li=[11,22,33]
func(li)
print(li)
[11,22,33,123]
2、lambda表达式
f4(函数名)=lambda 参数:reture值
3、内置函数
1、dict() 创建字典、 list() 创建列表 、str()创建字符串、 tuple()创建元祖、 floot()浮点、 input()等待用户输入、
round()四舍五入、len()计算长度(除整数)、max()取最大值、 min()取最小值、 print()打印、type()查看类型、
reversed()反转、 sum(可迭代的对象)求和、range()循环但不输出、
2、abs() 取绝对值
a=abs(-2)
print(a)
2
3、all()循环参数,如果每个元素都为真,则返回True,只要有一个元素为假,则返回False
If the iterable is empty, return True
如果all里面只有一个空,则为真
4、any()循环参数,只要有一个元素为真,则返回True
If the iterable is empty, return False
如果any里面只有一个空,则为假
5、ascii() 去输入的元素的类中找__repr__方法,获取其返回值
li=[]
a=ascii(li)
print(a)
[]
6、bin(数字) 二进制表示
a=bin(6)
print(a)
0b110
7、oct() 八进制表示
a=oct(6)
print(a)
0o6
8、int() 十进制表示
a=int(6)
print(a)
6
9、hex()十六进制表示
a=hex(6)
print(a)
0x6
10、各种进制之间的转换
其他进制相互转只有一种方式 oct(其他进制)
其他的相互转换有俩种方式 int(其他进制数字)或 int(“其他进制数字”,base=进制)
>>> oct(x)
>>> hex(x)
>>> bin(x)
>>> int(x)
>>>int(x,base=x)
a=hex(6)
print(a)
b=int("0x6",base=16)
print(b)
0x6
6
11、bool() 判断真假,把一个对象转换成布尔值
布尔值为False: [], {}、(), "" , 0, None
a=bool("")
print(a)
False
12、 bytes() 字节 bytearray() 字节列表
字符串和字节之间的转换
#字符串转字节
a=bytes("中国人",encoding="utf-8")
print(a)
b'\xe4\xb8\xad\xe5\x9b\xbd\xe4\xba\xba' #字节转字符串
b=str(a,encoding="utf-8")
print(b)
中国人
13、chr() 将传入的数字转换成ascii中所对应的元素
a=chr(66)
print(a)
B
14、ord() 将传入的元素转换成ascii中对应的数字
a=ord("a")
print(a)
97
15、random 一个模块,可以随机产生一个元素
import random
a=random.randrange(65,90)
print(a)
16、验证码
import random
b=""
for i in range(6):
c=random.randrange(0,4)
if c==1 or c==3:
d=random.randrange(0,9)
b=b+str(d)
else:
a=random.randrange(65,80)
b=b+chr(a)
print(b)
17、callable() 检查产生可否被执行,可执行返回True,否则返回False
def f1()
reture 123
a=callable(f1)
print(a)
True
18、dir() 查看对象类中的方法 help()
a=dic(str())
print(a)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
19、divmod() 用于运算俩个数的除法,并把商和余数放到元祖中
a=divmod(10,3)
print(a)
(3, 1)
20、eval() 可以执行一个字符串形式的表达式(字符串里面只能是数字)
a="1+2"
b=eval(a)
print(b)
3
b=eval("a+2",{"a":1}) #eval后可以接收参数(字典),用来申明变量
print(b)
3
21、exec() 用于执行.py代码
exec("for i in range(4):print(i)")
0
1
2
3
22、filter(函数,可迭代的) 将可迭代的每一个参数传入函数中,如果返回True 则输出参数,反之则过滤掉
def z(a):
if a>3:
return True
else:
return False
ret=filter(z,[1,2,3,4,5,])
print(ret)
for i in ret:
print(i)
<filter object at 0x0000001EA85B9550> #此处相当于range() 不直接输出浪费内存
4
5
def z(a):
return a+12
ret=filter(z,[1,2,3,4,5,])
print(ret)
for i in ret:
print(i)
<filter object at 0x0000000F9EE49550>
1
2
3
4
5
23、map(函数,可迭代的) 将可迭代的每一个参数传入函数中,执行函数体中的运算,并将运算值输出
def z(a):
return a+12
ret=map(z,[1,2,3,4,5,])
print(ret)
for i in ret:
print(i)
<map object at 0x00000082DC909550>
13
14
15
16
17
24、frozenset() 一个冻结的set,不可添加元素
25、global() 获取全局变量,并可以改变全局变量,locals() 获取局部变量
def z():
name="123"
print(globals())
print(locals())
z()
{'z': <function z at 0x000000751D4EAC80}
{'name': '123'}
26、hash() 用于保存优化字典里面的k值
dict={"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq":1}
a=hash("qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq")
print(a)
936761249792483134
27、isinstannce() 判断是否是同一个类
li=list()
r=isinstance(li,list)
print(r)
True
28、iter() 创建一个可以迭代的对象,迭代的对象执行next时,取下一个值。
a=iter([1,2,3])
print(a)
b1=next(a)
print(b1)
b2=next(a)
print(b2)
b3=next(a)
print(b3)
<list_iterator object at 0x0000005D5C239550>
1
2
3
29、pow() 求幂
a=pow(2,10)
print(a)
1024
30、zip() 将多个可迭代的类型,按照索引位置一一对应组合起来
a=[1,2,3,4]
b=[5,6,7,8]
c=(1,2,3,4)
d=zip(a,b,c)
print(d)
for i in d:
print(i)
<zip object at 0x000000DB794F0E88>
(1, 5, 1)
(2, 6, 2)
(3, 7, 3)
(4, 8, 4)
**31、sorted()为对象(都是同一种类型)排序,得到新值
a=[1,2,3,4,1212,13,4,56,7]
b=a.sort() #执行sort方法
print(a)
[1, 2, 3, 4, 4, 7, 13, 56, 1212]
1>数字排序
a=[1,2,3,4,1212,13,4,56,7]
b=sorted(a) #执行sort方法得到新值
print(b)
[1, 2, 3, 4, 4, 7, 13, 56, 1212]
2>字符串排序
char=['赵',"123", "1", "25", "65","679999999999","a","B","alex","c" ,"A", "_", "ᒲ",'a钱','孙','李',"余", '佘',"佗", "㽙", "铱", "钲钲㽙㽙㽙"] new_chat = sorted(char)
print(new_chat)
for i in new_chat:
print(bytes(i, encoding='utf-8'))
['1', '123', '25', '65', '679999999999', 'A', 'B', '_', 'a', 'alex', 'a钱', 'c', 'ᒲ', '㽙', '佗', '佘', '余', '孙', '李', '赵', '钲钲㽙㽙㽙', '铱']
b'1'
b'123'
b'25'
b'65' b'679999999999' #字符串中是数字的按数字大小排序(从左边第一位开始)
b'A'
b'B'
b'_'
b'a'
b'alex'
b'a\xe9\x92\xb1'
b'c' #大写的字母排到前面,小写的在后面,再看第一位(左边第一位)
b'\xe1\x92\xb2'
b'\xe3\xbd\x99'
b'\xe4\xbd\x97'
b'\xe4\xbd\x98'
b'\xe4\xbd\x99'
b'\xe5\xad\x99'
b'\xe6\x9d\x8e'
b'\xe8\xb5\xb5'
b'\xe9\x92\xb2\xe9\x92\xb2\xe3\xbd\x99\xe3\xbd\x99\xe3\xbd\x99'
b'\xe9\x93\xb1' #数字按照xe后跟的先排
***open()函数 用于处理文件
文件句柄 = open('文件路径', '模式')
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作
打开文件的模式有:
基本操作
普通打开()
a=open("111.py","r",encoding="utf-8") python 以r方式打开的时候把必须注明编码方式(文本中有汉字的情况)
- r ,只读模式【默认】
- w,只写模式【不可读;不存在则创建;存在则清空内容;】
- x, 只写模式【不可读;不存在则创建,存在则报错】
- a, 追加模式【不可读; 不存在则创建;存在则只追加内容;
"b"表示以字节的方式操作
- rb 或 r+b
- wb 或 w+b
- xb 或 w+b
- ab 或 a+b
"+" 表示可以同时读写某个文件
- r+, 读写【可读,可写】
- w+,写读【可读,可写】
- x+ ,写读【可读,可写】
- a+, 写读【可读,可写】
seek(参数) 用于调整指针位置
tell() 用于获取指针位置
read(参数)加参数用于读前几个字符
r+ 表示可读,可写
先读后写:能读到全部内容,指针移动到最后面,在内容后面追加内容(无论read(参数)中参数是几,后面再写的话指针都是在最后,但再读得话是按照前面读以后指针的位置作为起点)————————关闭文件前
a=open("334.txt","r+" ,encoding="utf-8")
b=a.read()
a.write("fgh")
a.close()
print(b)
123
先写后读:指针在开始位置,写入的内容把以前的覆盖掉,指针移动到写完后的位置,读取到写完后的内容
a=open("334.txt","r+",encoding="utf-8")
a.write("fgh")
c=a.read()
a.close()
print(c)
w+ 先清空,再写之后指针在末端,利用seek(参数)调整指针位置就可以读了
a=open("334.txt","w+")
print(a.tell())
a.write("asd")
a.seek(0)
b=a.read()
a.close()
print(b)
x+ 同w+,如果文件存在则报错
a+ 打开的同时指针移动到最后
先读后写:一开始指针再最后读取不到内容
先写后读:在内容后面追加内容,调整指针位置可以读取到内容
操作
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
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
flush(self): 刷新文件内部缓冲区
如果进程没有结束(用input(“ssss”)),write(“assds”)的内容就没有刷到硬盘中,读取不出来,加上福禄寿flush()就能够强制把内容刷到硬盘,不结束进程也能读取到
read(参数):
没有加参数读取所有内容,加上参数表示读取几个字符(以r方式打开)或几个字节(以rb方式打开)
readline():仅读取一行数据
truncate(self, *args, **kwargs): 截断数据,仅保留指定之前数据 依赖于指针的位置
a=open("334.txt","r+")
print(a.tell())
print(a.seek(5))
a.truncate()
a.close() 0 5 #用于截取文件内容中前五个字符串的内容
f=open("111.py',"r+",encoding="utf-8") #f是可以循环的
for line in f:
print(line) #可以把内容一行一行的读出来,可以看到内容的最后一行
管理上下文
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
with open("xxx","xx",encoding="utf-8") as f: pass
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:
with open('log1') as obj1, open('log2') as obj2: pass