首页 > 代码库 > Python基础(3)
Python基础(3)
set集合
set是一个无序且不重复的元素集合
优点:访问速度快
天生解决重复问题
重要一点的:
add
clear
copy
difference 比对两个列表中有什么不同的地方,然后生成一个新的set
dirrerence_update 你给我传什么我就移除什么
discard
intersection 取交集,新创建一个set
intersection_update 和上面一样一个修改原来的,一个生成新的
isdisjoint 如果没有交集,返回true
issubset 是否是子集
issuperset 是否是浮集
pop 移除并取出,将里面的元素拿出来
remove 移除
update 更新
collections系列
Counter是对字典类型的补充,用于追踪值的出现次数。
计数器(counter)
字典里所有的方法他都有,继承了父类
.Counter
1 import collections 2 3 xm = collections.Counter(‘abcdefgijkabcd111~!@‘) 4 # elements => 原生的值 5 # xm => 处理完的值 6 print(xm) Counter({‘1‘: 3, ‘a‘: 2, ‘b‘: 2, ‘c‘: 2, ‘d‘: 2, ‘e‘: 1, ‘f‘: 1, ‘g‘: 1, ‘i‘: 1, ‘j‘: 1, ‘k‘: 1, ‘~‘: 1, ‘!‘: 1, ‘@‘: 1})
.most_common(x) 拿到前x位的统计
.elements() 取counter的key 打印所有的元素,不打印个数也就是v
import collections xm = collections.Counter(‘abcdefgijkabcd111~!@‘) j = xm.most_common(2) print(j) for key in xm.elements(): print(key) for keys, values in xm.items(): print(keys, values) d 2 e 1 f 1 g 1 i 1 j 1 k 1 1 3 ~ 1 ! 1 @ 1
update 更新 相加
subtract 相减 会出现负数
系列2
有序字典(orderedDict)
orderdDict是对字典类型的补充,他记住了字典元素添加的顺序
.move_to_end(‘’) 将其转到最后
.popitem() 去除添加时间最晚的一个 后进先出
.pop() 想取哪个取哪个
.setdefault(x,y) 设置默认值 默认为None
这两个相等
默认字典 defaultdict
改进刚刚的小练习
自带的功能
再加上字典的功能
可命名元组(namedtuple)
根据nametuple可以创建一个包含tuple所有功能以及其他功能的类型。
这个比其他的多一个步骤,要创建一个类,他没有提供类,然后才能根据类创建对象
双向队列(deque)
一个线程安全的双向队列
reverse反转
rotate 将最后一个或几个插到第一个
单向队列
既然有双向队列,也有单项队列(先进先出 FIFO )
qsize 看队列里的个数
full 看是否填满了
put 添加
get 取出
深浅拷贝
1 import copy 2 n1 = {"k1":"v1","k2":"v2","k3":"v3"} 3 n2 = n1 4 print(id(n1)) 5 print(id(n2)) 6 n3=copy.copy(n1) 7 print(id(n3))
上面的代码为浅拷贝,浅拷贝是在内存中只额外创建第一层数据,也就是只复制了第一层
深拷贝,在内存中将所有的数据都重新创建一份,在拷贝字典的时候会将里面的也拷贝,id不一样(排除最后一层, 既python内部对字符串和数字 的优化)
import copy dic = { "cpu":[80,], "mem":[80,], "disk":[80,] } print(dic) new_dic =copy.deepcopy(dic) new_dic[‘cpu‘][0]=50 print(new_dic) {‘cpu‘: [80], ‘mem‘: [80], ‘disk‘: [80]} {‘cpu‘: [50], ‘mem‘: [80], ‘disk‘: [80]}
函数
def mail(): n = 123 n += 1 print(n) mail() f= mail f()
这样f()=mail()
自定义一个发送邮件的函数:
import smtplib from email.mime.text import MIMEText from email.utils import formataddr def mail(): ret = True try: msg = MIMEText(‘邮件内容‘,‘plain‘,‘utf-8‘) msg[‘From‘] = formataddr(["su",‘xxxx@qq.com‘]) msg[‘To‘] = formataddr(["666",‘xxxx@qq.com‘]) msg[‘Subject‘]="主题" server = smtplib.SMTP("smtp.qq.com",465) server.login("xxxx@qq.com","密码") server.sendmail(‘xxxx@qq.com‘,[‘xxxx@qq.com‘,],msg.as_string()) server.quit() except Exception: ret = False return ret ret = mail() if ret: print(‘发送成功‘) else: print(‘发送失败‘)
参数
一个参数
def show(arg): print(arg,type(arg)) show(1,2,3,45,)
两个参数
def show(arg,arg21): #顺序不能乱 一个* 的在前 print(arg,type(arg)) print(arg21,type(arg21)) show(11,223,45,n1=123,n2=456)
默认参数
默认参数可以有很多,但是必须放在最后面 也是就xx=xxx这个必须在后面
指定参数 就指定一个
动态参数
def show(*arg): print(arg,type(arg)) show(1,2,3,45,) def show(**arg21): print(arg21,type(arg21)) show(n1=123,n2=4) def show(*arg,**arg21): #顺序不能乱 一个* 的在前 print(arg,type(arg)) print(arg21,type(arg21)) show(11,223,45,n1=123,n2=456)
l= (11,22,33)
print(l)
x={‘m‘:1,‘n‘:3}
#show(l,x) #不行 ,需要加*
show(*l,**x)
s1 = "{name} no {acter}"
d={‘name‘:‘abc‘,‘acter‘:‘123‘}
result= s1.format(**d)
print(result)
s1 = "{0} no {1}"
l =[‘abc‘,‘123‘]
result = s1.format(*l)
print(result)
多个参数
ps:( format它通过{}和:来代替%。
“映射”示例
通过位置
In [1]: ‘{0},{1}‘.format(‘kzc‘,18)
Out[1]: ‘kzc,18‘
In [2]: ‘{},{}‘.format(‘kzc‘,18)
Out[2]: ‘kzc,18‘
In [3]: ‘{1},{0},{1}‘.format(‘kzc‘,18)
Out[3]: ‘18,kzc,18‘ )
lambda表达式 简单函数的表示
内置函数
all() :里面的元素全是真返回TRUE,有一个假返回false
ps: None,0,空字符串,元组,字典都是假的
any() : 一个为真 返回TRUE
bin() :二进制
bool() :布尔
callable(): 能否被执行
chr() :数字转成ASCII码 动态验证码能用到
enumerate() :
filter(函数等,列表元组等) :过滤,只显示TRUE
frozenset():不能增加与修改的集合
globals():所有的可用变量,全局变量
hash():用来做字典的k的时候用的 将他转为hash值
hex():转为16进制
max():拿最大值
oct():八进制
open():打开文件
pow():幂
range():拿他的区间
round():四舍五入的
zip():
open()函数 该函数用于文件处理
操作文件时,一般需要经历如下步骤:
- 打开文件
- 操作文件
一、打开文件
1
|
文件句柄 = file ( ‘文件路径‘ , ‘模式‘ ) |
注:python中打开文件有两种方式,即:open(...) 和 file(...) ,本质上前者在内部会调用后者来进行文件操作,推荐使用 open。
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+,可读写文件。【可读;可写;可追加】
- w+,写读
- a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb
- wb
- ab
二、操作操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
|
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 0 (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 |
f.read ()是通过字符拿,不是字节
tell() 读出有多少字节
ps:中文3个字节
seek(): 指定指针位置
trancate(x) : 只剩前x位的内容,后面的去掉了
Python基础(3)