Python Set集合,函数,深入拷贝,浅入拷贝,文件处理


1、Set基本数据类型

a、set集合,是一个无序且不重复的元素集合

复制代码
class set(object):
    """
    set() -> new empty set object
    set(iterable) -> new set object
     
    Build an unordered collection of unique elements.
    """
    def add(self, *args, **kwargs): # real signature unknown
        """
        Add an element to a set,添加元素
         
        This has no effect if the element is already present.
        """
        pass
 
    def clear(self, *args, **kwargs): # real signature unknown
        """ Remove all elements from this set. 清楚内容"""
        pass
 
    def copy(self, *args, **kwargs): # real signature unknown
        """ Return a shallow copy of a set. 浅拷贝  """
        pass
 
    def difference(self, *args, **kwargs): # real signature unknown
        """
        Return the difference of two or more sets as a new set. A中存在,B中不存在
         
        (i.e. all elements that are in this set but not the others.)
        """
        pass
 
    def difference_update(self, *args, **kwargs): # real signature unknown
        """ Remove all elements of another set from this set.  从当前集合中删除和B中相同的元素"""
        pass
 
    def discard(self, *args, **kwargs): # real signature unknown
        """
        Remove an element from a set if it is a member.
         
        If the element is not a member, do nothing. 移除指定元素,不存在不保错
        """
        pass
 
    def intersection(self, *args, **kwargs): # real signature unknown
        """
        Return the intersection of two sets as a new set. 交集
         
        (i.e. all elements that are in both sets.)
        """
        pass
 
    def intersection_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the intersection of itself and another.  取交集并更更新到A中 """
        pass
 
    def isdisjoint(self, *args, **kwargs): # real signature unknown
        """ Return True if two sets have a null intersection.  如果没有交集,返回True,否则返回False"""
        pass
 
    def issubset(self, *args, **kwargs): # real signature unknown
        """ Report whether another set contains this set.  是否是子序列"""
        pass
 
    def issuperset(self, *args, **kwargs): # real signature unknown
        """ Report whether this set contains another set. 是否是父序列"""
        pass
 
    def pop(self, *args, **kwargs): # real signature unknown
        """
        Remove and return an arbitrary set element.
        Raises KeyError if the set is empty. 移除元素
        """
        pass
 
    def remove(self, *args, **kwargs): # real signature unknown
        """
        Remove an element from a set; it must be a member.
         
        If the element is not a member, raise a KeyError. 移除指定元素,不存在保错
        """
        pass
 
    def symmetric_difference(self, *args, **kwargs): # real signature unknown
        """
        Return the symmetric difference of two sets as a new set.  对称交集
         
        (i.e. all elements that are in exactly one of the sets.)
        """
        pass
 
    def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the symmetric difference of itself and another. 对称交集,并更新到a中 """
        pass
 
    def union(self, *args, **kwargs): # real signature unknown
        """
        Return the union of sets as a new set.  并集
         
        (i.e. all elements that are in either set.)
        """
        pass
 
    def update(self, *args, **kwargs): # real signature unknown
        """ Update a set with the union of itself and others. 更新 """
        pass
复制代码

b、数据类型模块举例

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
se  =  { 11 , 22 , 33 , 44 , 55 }
be  =  { 44 , 55 , 66 , 77 , 88 }
 
 
# se.add(66)
# print(se)    #添加元素,不能直接打印!
#
#
#
# se.clear()
# print(se)          #清除se集合里面所有的值,不能清除单个
#
#
#
# ce=be.difference(se)   #se中存在,be中不存在的值,必须赋值给一个新的变量
# print(ce)
#
#
# se.difference_update(be)
# print(se)                  #在se中删除和be相同的值,不能赋值给一个新的变量,先输入转换,然后打印,也不能直接打印!
 
# se.discard(11)
# print(se)                   #移除指定元素,移除不存在的时候,不会报错
 
# se.remove(11)
# print(se)              #移除指定的元素,移除不存在的会报错
 
# se.pop()
# print(se)               #移除随机的元素
#
#
# ret=se.pop()
# print(ret)              #移除元素,并且可以把移除的元素赋值给另一个变量
 
 
 
# ce = se.intersection(be)
# print(ce)        #取出两个集合的交集(相同的元素)
 
 
# se.intersection_update(be)
# print(se)        #取出两个集合的交集,并更新到se集合中
 
# ret = se.isdisjoint(be)
# print(ret)         #判断两个集合之间又没有交集,如果有交集返回False,没有返回True
 
# ret=se.issubset(be)
# print(ret)         #判断se是否是be集合的子序列,如果是返回True,不是返回Flase
 
# ret = se.issuperset(be)
# print(ret)          #判断se是不是be集合的父序列,如果是返回True,不是返回Flase
 
# ret=se.symmetric_difference(be)
# print(ret)          #对称交集,取出除了不相同的元素
 
# se.symmetric_difference_update(be)
# print(se)          #对称交集,取出不相同的元素并更新到se集合中
 
# ret = se.union(be)
# print(ret)         #并集,把两个元素集合并在一个新的变量中

 

2、深浅拷贝

a、数字和字符串

    对于 数字 和 字符串 而言,赋值、浅拷贝和深拷贝无意义,因为其永远指向同一个内存地址。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import  copy
# ######### 数字、字符串 #########
n1  =  123
# n1 = "i am alex age 10"
print ( id (n1))
# ## 赋值 ##
n2  =  n1
print ( id (n2))
# ## 浅拷贝 ##
n2  =  copy.copy(n1)
print ( id (n2))
   
# ## 深拷贝 ##
n3  =  copy.deepcopy(n1)
print ( id (n3))

 

 b、其他基本数据类型

对于字典、元祖、列表 而言,进行赋值、浅拷贝和深拷贝时,其内存地址的变化是不同的。

1、赋值

赋值,只是创建一个变量,该变量指向原来内存地址,如:

1
2
3
n1  =  { "k1" "zhangyanlin" "k2" 123 "k3" : [ "Aylin" 456 ]}
   
n2  =  n1

 

2、浅拷贝

浅拷贝,在内存中只额外创建第一层数据

1
2
3
4
5
import  copy
   
n1  =  { "k1" "zhangyanlin" "k2" 123 "k3" : [ "aylin" 456 ]}
   
n3  =  copy.copy(n1)

  

3、深拷贝

深拷贝,在内存中将所有的数据重新创建一份(排除最后一层,即:python内部对字符串和数字的优化)

3、函数
  • 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可
  • 面向对象:对函数进行分类和封装,让开发“更快更好更强...
  • 函数传参数传的是引用

 

.函数的定义主要有如下要点:

  • def:表示函数的关键字
  • 函数名:函数的名称,日后根据函数名调用函数
  • 函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等...
  • 参数:为函数体提供数据
  • 返回值:当函数执行完毕后,可以给调用者返回数据。

1、返回值

函数是一个功能块,该功能到底执行成功与否,需要通过返回值来告知调用者。

以上要点中,比较重要有参数和返回值:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def  发送短信():
        
     发送短信的代码...
    
     if  发送成功:
         return  True
     else :
         return  False
    
    
while  True :
        
     # 每次执行发送短信函数,都会将返回值自动赋值给result
     # 之后,可以根据result来写日志,或重发等操作
    
     result  =  发送短信()
     if  result  = =  False :
         短信发送失败...

  

函数的有三中不同的参数:

  • 普通参数
1
2
3
4
5
6
7
8
9
# ######### 定义函数 #########
 
# name 叫做函数func的形式参数,简称:形参
def  func(name):
     print  name
 
# ######### 执行函数 #########
#  'zhangyanlin' 叫做函数func的实际参数,简称:实参
func( 'zhangyanlin' )

  

  • 默认参数
1
2
3
4
5
6
7
8
9
10
def  func(name, age  =  18 ):
     
     print  "%s:%s"  % (name,age)
 
# 指定参数
func( 'zhangyanlin' 19 )
# 使用默认参数
func( 'nick' )
 
注:默认参数需要放在参数列表最后

  

  • 动态参数
1
2
3
4
5
6
7
8
9
10
11
def  func( * args):
 
     print  args
 
 
# 执行方式一
func( 11 , 33 , 4 , 4454 , 5 )
 
# 执行方式二
li  =  [ 11 , 2 , 2 , 3 , 3 , 4 , 54 ]
func( * li)

  

1
2
3
4
5
6
7
8
9
10
11
def  func( * * kwargs):
 
     print  args
 
 
# 执行方式一
func(name= 'wupeiqi' ,age = 18 )
 
# 执行方式二
li  =  { 'name' : 'wupeiqi' , age: 18 'gender' : 'male' }
func( * * li)

  

1
2
3
4
def  func( * args,  * * kwargs):
 
     print  args
     print  kwargs

邮件实例:

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
def  email(p,j,k):
     import  smtplib
     from  email.mime.text  import  MIMEText
     from  email.utils  import  formataddr
 
     set  =  True
     try :
         msg  =  MIMEText( 'j' 'plain' 'utf-8' )   #j 邮件内容
         msg[ 'From' =  formataddr([ "武沛齐" , 'wptawy@126.com' ])
         msg[ 'To' =  formataddr([ "走人" , '424662508@qq.com' ])
         msg[ 'Subject' =  "k"   #k主题
 
         server  =  smtplib.SMTP( "smtp.126.com" 25 )
         server.login( "wptawy@126.com" "WW.3945.59" )
         server.sendmail( 'wptawy@126.com' , [p], msg.as_string())
         server.quit()
     except :
         set  =  False
     return  True
 
 
formmail  =  input ( "请你输入收件人邮箱:" )
zhuti     =  input ( "请您输入邮件主题:" )
neirong   =  input ( "请您输入邮件内容:" )
aa = email(formmail,neirong,zhuti)
if  aa:
     print ( "邮件发送成功!" )
else :
     print ( "邮件发送失败!" )

 

2、 内置函数

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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# abs绝对值
# i = abs(-123)
# print(i)  #返回123,绝对值
 
 
# #all,循环参数,如果每个元素为真,那么all返回的为真,有一个为假返回的就是假的
# a = all((None,123,456,False))
# print(a)   #返回的为假的,证明中间有False值
#
# #所有的假值有
#     #0,None,空值
#
 
# #any  只要之前有一个是真的,返回的就是真
# b = any([11,False])
# print(b)
 
 
#ascii,去指定对象的类中找__repr__,获取返回值
# #ascii函数
# class Foo:
#     def __repr__(self):
#         return "zhangyanlin"
# obj =Foo()
# r = ascii(obj)
# print(r)
 
 
# 布尔值返回真或假
# print(bool(1))
# print(bool(0))
 
 
 
 
# #bin二进制
# r = bin(123)
# print(r)
 
# #oct八进制
# r = oct(123)
# print(r)
 
# #int十进制
# r = int(123)
# print(r)
 
# #hex十六进制
# r = hex(123)
# print(r)
 
# #二进制转十进制
# i= int("0b11",base=2)
# print(i)
 
# #八进制转十进制
# i= int("11",base=8)
# print(i)
 
# #十六进制转十进制
# i = int("0xe",base=16)
# print(i)
 
# #数字代表字母
# c = chr(66)
# print(c)
 
# #字母代表数字
# c = ord("a")
# print(c)
 
 
#bytes,  字节
#字节和字符串的转换
# a = bytes("zhangyanlin",encoding="utf-8")
# print(a)
#bytearray  字节列表
 
 
 
#chr(),把数字转换成字母,只适用于ascii码
# a = chr(65)
# print(a)
 
#ord(),把字母转换成数字,只适用于ascii码
# a = ord("a")
# print(a)
 
#callable表示一个对象是否可执行
# def f1():        #看这个函数能不能执行,能发挥True
#     return 123
# f1()
# r = callable(f1)
# print(r)
 
 
 
#dir,查看一个类里面存在的功能
# li = []
# print(dir(li))
# help(list)
 
 
#divmod(),#分页的时候使用
# a = 10/3
# r = divmod(10,3)
# print(r)
 
 
 
#compile编译, 把字符串转移成python可执行的代码,知道就行
 
#eval(),简单的表达式,可以给算出来
# b = eval("a + 69" , {"a":99})  #a可以通过字典声明变量去写入
# print(b)
 
#exec,不会返回值,直接输出结果
# exec("for i in range(10):print(i)")
 
 
# filter对于序列中的元素进行筛选,最终获取符合条件的序列(需要循环)
# def f1(x):
#     if x >22:
#         return  True
#     else:
#         return False
#
# ret = filter(f1,[11,22,33,44,55])
# for i in ret:
#     print(i)
 
# ret = filter(lambda x: x > 22, [11, 22, 33, 44, 55, 66, 77])
# for i in ret:
#     print(i)
 
#map(函数,可以迭代的对象,让元素统一操作)
# def f1(x):
#     return x+123
#
# # li = [11,22,33,44,55,66]
# # ret = map(f1,li)
# print(ret)
# for i in ret:
#     print(i)
#
# ret = map(lambda x: x + 100 if x%2==1 else x, [11, 22, 33, 44])
# print(ret)
# for i in ret:
#     print(i)
 
#globals()获取当前所有的全局变量
 
#locals()获取当前所有的局部变量
# ret = "kaszhfiusdhf"
# def fu1():
#     name = 123
#     print(locals())
#     print(globals())
#
# fu1()
 
 
#hash 对key的优化,相当于给输出一种哈希值
# li = "sdglgmdgongoaerngonaeorgnienrg"
# print(hash(li))
 
#isinstance()判断是不是一个类型
# li = [11,22]
# ret = isinstance(li,list)
# print(ret)
 
 
#iter创建一个可以被迭代的元素
# obj = iter([11,22,33,44])
# print(obj)
# #next,取下一个值,一个变量里的值可以一直往下取,直到没有就报错
# ret = next(obj)
 
#max()取最大的值
# li = [11,22,33,44]
# ret = max(li)
# print(ret)
 
#min()取最小值
# li = [11,22,33,44]
# ret = min(li)
# print(ret)
 
#求一个数字的多少次方
# ret = pow(2,10)
# print(ret)
 
#reversed反转
# a = [11,22,33,44]
# b = reversed(a)
# for i in b:
#     print(i)
 
#round 四舍五入
# ret = round(4.8)
# print(ret)
 
#sum求和
# ret = sum((11,22,33,44))
# print(ret)
 
#zip,1 1对应
# li1 = [11,22,33,44,55]
# li2 = [99,88,77,66,89]
# dic = dict(zip(li1,li2))
# print(dic)
 
 
#sorted 排序
# li = ["1","2sdg;l","57","a","b","A","中国人"]
# lis = sorted(li)
# print(lis)
# for i in lis:
#     print(bytes(i,encoding="utf-8"))
 
 
 
 
# #随机生成6位验证码
# import random
# temp = ''
# for i in range(6):
#     num = random.randrange(0,4)
#     if num ==3 or num ==1:
#         rad1 = random.randrange(0,10)
#         temp+=str(rad1)
#     else:
#         rad2 = random.randrange(65,91)
#         c1 = chr(rad2)
#         temp+=c1
# print(temp)

 

 

4、文件处理

a、打开文件

1
name  =  open ( '文件路径' '模式' )

打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

打开文件的模式有:

  • r ,只读模式【默认】
  • w,只写模式【不可读;不存在则创建;存在则清空内容;】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【不可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】

 "b"表示以字节的方式操作

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

 

例:

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
#普通方式打开
# ====pythobnn内部将二进制转换成字符串,通过字符串操作
 
#二进制打开方式
#用户自己操作把字符串转成二进制,然后让电脑识别
 
 
# 1. 只读模式,r
# a = open("1.log","r")   #打开1.log,赋予只读的权限
# ret = a.read()        #读取文件
# a.close()            #退出文件
# print(ret)             #打印文件内容
 
#2.只写模式,w, 如果不存在会创建文件,存在则清空内容
# a = open("3.log","w")
# a.write("sdfhsuigfhuisg")
# a.close()
 
#3.只写模式,x, 如果不存在会创建文件,存在则报错
# a = open("4.log","x")
# a.write("12345678")
# a.close()
 
#4.追加模式,a,不可读,不存在则创建文件,存在则会追加内容
# a = open("4.log","a")
# a.write("asjfioshf")
# a.close()
 
# "b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
 
#5.只读模式,rb,以字节方式打开,默认打开是字节的方式
# a = open("2.log","rb")    #二进制方式读取2.log文件
# date = a.read()            #定义变量,读文件
# a.close()                  #关闭文件
# print(date)                #打印文件
# str_data = str(date, encoding="utf-8")    #字节转换成utf-8
# print(str_data)            # 打印文件
 
 
#6.只写模式,wb,
# a = open("2.log","wb")     #打开文件2.log,可写的模式
# date = "中国人"             #定义字符串
# a.write(bytes(date , encoding="utf-8")) #转换成字节,方便计算机识别
# a.close()                    #关闭文件
# print(date)                  #打印出来
 
 
 
#7.只写模式,xb,
# a = open("6.log","xb")
# date = "张岩林非常帅"
# # a.write("sakfdhisf")   #字符串形式会报错,计算机不识别,得转换成字节
# a.write(bytes(date,encoding="utf-8"))
# a.close()
# print(date)
 
 
#8.追加模式,ab,
# a = open("5.log","ab")
# date = "!张岩林是个帅小伙子"
# a.write(bytes(date,encoding="utf-8"))
# a.close()
# print(date)
 
 
 
# #"+"表示具有读写的功能
 
# #9.r+,读写(可读,可写)
# a = open("5.log","r+",encoding="utf-8")
# print(a.tell())    #打开文件后观看指针位置在第几位,默认在起始位置
#
# date = a.read()       #第一次读取,指针读取到最后了,(可以加读取的索引位置,3表示只看前三位)
# print(date)
#
# a.write("太帅了")      #写的时候会把指针调到最后去写
#
# a.seek(0)           #把指针放在第一位进行第二次读取
#
# date = a.read()       #第二次读取
# print(date)
# a.close()
 
 
#10.w+,写读,(可写,可读),先清空内容,在写之后需要把指针放在第一位才能读
# a = open("5.log","w+",encoding="utf-8")
# a.write("张岩林")        #清空内容写入“张岩林”
# a.seek(0)                 #把指针放在第一位
# date = a.read()           #进行读取
# a.close()                 #退出文件
# print(date)
 
 
 
#11.x+,写读,(可写,可读),需要创建一个新文件,文件存在会报错,在写之后需要把指针放在第一位才能读
# a = open("7.log","x+",encoding="utf-8")
# a.write("张岩林")        #清空内容写入“张岩林”
# a.seek(0)                 #把指针放在第一位
# date = a.read()           #进行读取
# a.close()                 #退出文件
# print(date)
 
 
#12.a+,写读,(可写,可读),打开文件的同时,指针已经在最后了
# a = open("5.log","a+",encoding="utf-8")
# date = a.read()          #第一次读,没数据,因为指针在最后
# print(date)
#
# a.write("张张")          #往最后写入 张
#
# a.seek(0)                #把指针放在第一位,让他进行曲读
# date = a.read()
# print(date)
#
# a.close()

  

 

b、操作操作

 

复制代码
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
复制代码

 

复制代码
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
复制代码

 

1
2
3
4
5
6
7
8
9
=  open ( "5.log" , "r+" ,encoding = "utf-8" )
# a.truncate()     #依赖于指针,截取数据,只剩下指针所在位置的前面的数据
# a.close()        #关闭
# a.flush()        #强行加入内存
# a.read()         #读
# a.readline()     #只读取第一行
# a.seek(0)        #指针
# a.tell()         #当前指针位置
# a.write()        #写

  

 

c、管理上下文

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

1
2
3
with  open ( 'log' , 'r' ) as f:
         
     ...

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:

1
2
with  open ( 'log1' ) as obj1,  open ( 'log2' ) as obj2:
     pass

例:

1
2
3
4
5
6
7
8
#关闭文件with
with  open ( "5.log" , "r" ) as a:
     a.read()
 
#同事打开两个文件,把a复制到b中,读一行写一行,直到写完
with  open ( "5.log" , "r" ,encoding = "utf-8" ) as a, open ( "6.log" , "w" ,encoding = "utf-8" ) as b:
     for  line  in  a:
         b.write(line)

  

lambda表达式

 

学习条件运算时,对于简单的 if else 语句,可以使用三元运算来表示,即:

1
2
3
4
5
6
7
8
# 普通条件语句
if  1  = =  1 :
     name  =  'wupeiqi'
else :
     name  =  'alex'
     
# 三元运算
name  =  'wupeiqi'  if  1  = =  1  else  'alex'

对于简单的函数,也存在一种简便的表示方式,即:lambda表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# ###################### 普通函数 ######################
# 定义函数(普通方式)
def  func(arg):
     return  arg  +  1
     
# 执行函数
result  =  func( 123 )
     
# ###################### lambda ######################
     
# 定义函数(lambda表达式)
my_lambda  =  lambda  arg : arg  +  1
     
# 执行函数
result  =  my_lambda( 123 )

 

递归

利用函数编写如下数列:

斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368...

1
2
3
4
5
6
7
8
def  func(arg1,arg2):
     if  arg1  = =  0 :
         print  arg1, arg2
     arg3  =  arg1  +  arg2
     print  arg3
     func(arg2, arg3)
   
func( 0 , 1 )
1
2
3
4
5
6
7
8
def  func(n,a,b):
     if  = =  10 :
         return  a
     =  +  b
     return  func(n + 1 ,b,c)
 
ret  =  func( 1 , 0 , 1 )
print (ret)
1
2
3
4
5
# 列出一组数据
a,b  =  0 , 1
while  b < 1000 :
     print (a)
     a, b  =  b, a +  b

  

 

冒泡排序

 

1
2
3
4
5
6
7
8
# li = [11,2,35,14,22,35235,1232141,345,321423,123,123234]
# for j in range(1,len(li)):
#     for i in range(len(li)-j):
#         if li[i]<li[i+1]:
#             temp = li[i]
#             li[i]=li[i+1]
#             li[i+1]=temp
# print(li)

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python集合是一种可变对象,因此浅拷贝可能会导致意外的结果。浅拷贝只是复制了集合对象本身,而不是其的元素。因此,如果你修改了浅拷贝集合,原始集合也会受到影响。 举个例子,假设你有一个集合`original_set`,它包含了一些元素。你想要创建一个新的集合`shallow_copy_set`,并且将`original_set`的元素复制到`shallow_copy_set`。你可以使用`copy()`方法来进行浅拷贝,如下所示: ``` original_set = {1, 2, 3} shallow_copy_set = original_set.copy() ``` 现在,你对`shallow_copy_set`进行了修改,添加了一个新的元素: ``` shallow_copy_set.add(4) ``` 如果你现在打印`original_set`,你会发现它也包含了新添加的元素4,这是因为它们共享了相同的元素对象。 为了避免这种情况,你可以使用深拷贝(`copy.deepcopy()`)来创建一个完全独立的集合副本,这样你就可以修改它而不会影响原始集合。 ### 回答2: 在Python,对于集合的浅拷贝是出错的。所谓浅拷贝是指创建一个新的对象,其包含原始对象的引用,而不是创建原始对象的副本。对于简单的数据类型如整数、字符串等,浅拷贝是可以正常工作的。但是对于集合类型,如列表、字典和集合本身,浅拷贝存在一些问题。 当我们使用浅拷贝来复制一个集合时,新的集合包含原始集合元素的引用。这意味着对新集合的修改也会影响原始集合,因为它们引用相同的对象。这在某些情况下可能会导致意外的结果,特别是在修改集合的可变对象时。 为了解决这个问题,我们可以使用深拷贝来创建一个集合的副本,其包含原始集合元素的副本而不是引用。深拷贝可以通过`copy`模块的`deepcopy`函数实现。深拷贝不仅会复制集合本身,还会递归复制其的每个对象,使得新集合与原始集合完全独立。 以下是一个简单的例子,展示了集合拷贝的问题: ``` import copy original_set = {1, 2, [3, 4]} shallow_copy = copy.copy(original_set) shallow_copy.add(5) print(original_set) # 输出 {1, 2, [3, 4], 5} shallow_copy[2].append(6) print(original_set) # 输出 {1, 2, [3, 4, 6], 5} ``` 从上面的例子可以看出,使用浅拷贝创建的新集合`shallow_copy`与原始集合`original_set`共享相同的列表对象。因此,对新集合的列表对象进行修改会影响原始集合。 综上所述,Python对于集合的浅拷贝会出错,需要使用深拷贝来复制集合以避免意外修改原始集合。 ### 回答3: Python集合set)是可变对象,而浅拷贝(shallow copy)是一种创建新对象的方式,新对象与原对象的元素是共享的。但是,集合存在一个特性,即其元素是唯一的,不允许重复。这就导致了在浅拷贝集合时可能会出现一些问题。 在进行集合的浅拷贝时,会创建一个指向原始集合的新对象,但是新对象和原始集合之间共享了同一组元素。这意味着在对新对象进行操作时,会影响到原始集合。 例如,我们有一个包含一些元素的集合A,然后通过浅拷贝创建了一个新的集合B。当我们向集合B添加一个元素时,原始集合A也会受到影响,因为它们共享同一组元素。这是因为集合的唯一性要求,在新对象添加的元素也会被加入到原始集合。 解决这个问题的一种方法是使用深拷贝(deep copy),它会创建一个全新的集合对象,其包含任何原始集合的元素。这样就能确保在对新对象进行操作时不会影响到原始集合。 可以使用copy模块的deepcopy函数来进行深拷贝操作,例如: ```python import copy setA = {1, 2, 3} setB = copy.deepcopy(setA) setB.add(4) print(setA) # 输出{1, 2, 3} print(setB) # 输出{1, 2, 3, 4} ``` 总之,由于集合的特性,使用浅拷贝会导致新对象和原对象共享同一组元素,进而影响到原始集合。如果需要创建一个完全独立的集合对象,可以使用深拷贝来解决这个问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值