python学习之路 第三天

1、set集合:去掉重复字段

     set.difference()找出不同并创建一个新的集合,不改变原来集合;

     set.difference_update() 改变原来集合,剔除掉括号内容;

     set.discard() 移除元素;

     set.intersection() 取交集;

     set.symmetric_difference() 对称差,差集。

 2、set.difference() 与 set.symmetric_difference() 对比

     #!/usr/bin/env python3

     s1 = set([11,22,33])
     s2 = set([22,44])
     ret1 = s1.difference(s2)
     ret2 = s1.symmetric_difference(s2)
     print(ret1)
     print(ret2)

     运行结果:{33, 11}  {33, 11, 44}   ret1只循环了s1,ret2循环了s1后又循环了s2,循环2次。

3、collections系列:

     counter 计数器;

     most_common 取前几位;

     elements() 原生的值;

     subtract() 相减,减去括号内出现的次数;

     orderedDict 有序字典;

     defaultdict 默认字典;

4、#!/usr/bin/env python3
     import collections
     f = collections.Counter('abcdabcdaabbd')
     print(f)

     运行结果:Counter({'a': 4, 'b': 4, 'd': 3, 'c': 2})

5、collections.namedtuple() 可命名元祖
     #!/usr/bin/env python3
     import collections
     mytupleclass = collections.namedtuple('mytupleclass',['x','y','z'])
     obj = mytupleclass(11,22,33)
     print(obj.x)
     print(obj.y)
     print(obj.z)

     运行结果:11 22 33

6、deque 队列

7、copy.copy() 浅拷贝

     copy.deepcopy() 深拷贝

    

     #!/usr/bin/env python3

     import copy

     dic = {     "cpu":[80],     "mem":[80],     "disk":[80] }

     print('before',dic)

     new_dic = copy.copy(dic)

     new_dic['cpu'][0] = 50

     print(dic)

     print(new_dic)

     运行结果:

     before {'cpu': [80], 'mem': [80], 'disk': [80]}

               {'cpu': [50], 'mem': [80], 'disk': [80]}

               {'cpu': [50], 'mem': [80], 'disk': [80]}

     #!/usr/bin/env python3

     import copy

     dic = {     "cpu":[80],     "mem":[80],     "disk":[80] }

     print('before',dic)

     new_dic = copy.deepcopy(dic)

     new_dic['cpu'][0] = 50

     print(dic)

     print(new_dic)

     运行结果:

     before {'cpu': [80], 'mem': [80], 'disk': [80]}

               {'cpu': [80], 'mem': [80], 'disk': [80]}

               {'cpu': [50], 'mem': [80], 'disk': [80]}

8、函数   

     #!/usr/bin/env python3

     import smtplib

     from email.mime.text import MIMEText

     from email.utils import formataddr

     def mail():    

         ret = 'success'    

         try:        

             msg = MIMEText('邮件内容','plain','utf-8')        

             msg['From'] = formataddr(["111",'1111@qq.com'])        

             msg['To'] = formataddr(["222",'2222@qq.com'])       

             msg['Subject'] = "主题"

             server = smtplib.SMTP("smtp.qq.com",25)

             server.login("1111@qq.com","输入邮箱密码")

             server.sendmail('1111@qq.com',['2222@qq.com',],msg.as_string())  

             server.quit()    

          except Exception:

              ret = 'fail'

          return ret

     ret = mail()

     print(ret)

     运行结果:fail,实验使用真实邮箱获得结果为success。

        

         

原文地址:https://www.cnblogs.com/yunv724/p/6212851.html