zoukankan      html  css  js  c++  java
  • python整理-Day3

    set

    无须,不重复,可嵌套的集合

      1 class set(object): 
      2     """ 
      3     set() -> new empty set object 
      4     set(iterable) -> new set object 
      5       
      6     Build an unordered collection of unique elements. 
      7     """
      8     def add(self, *args, **kwargs): # real signature unknown 
      9         """ 
     10         Add an element to a set,添加元素 
     11           
     12         This has no effect if the element is already present. 
     13         """
     14         pass
     15   
     16     def clear(self, *args, **kwargs): # real signature unknown 
     17         """ Remove all elements from this set. 清除内容"""
     18         pass
     19   
     20     def copy(self, *args, **kwargs): # real signature unknown 
     21         """ Return a shallow copy of a set. 浅拷贝  """
     22         pass
     23   
     24     def difference(self, *args, **kwargs): # real signature unknown 
     25         """ 
     26         Return the difference of two or more sets as a new set. A中存在,B中不存在 
     27           
     28         (i.e. all elements that are in this set but not the others.) 
     29         """
     30         pass
     31   
     32     def difference_update(self, *args, **kwargs): # real signature unknown 
     33         """ Remove all elements of another set from this set.  从当前集合中删除和B中相同的元素"""
     34         pass
     35   
     36     def discard(self, *args, **kwargs): # real signature unknown 
     37         """ 
     38         Remove an element from a set if it is a member. 
     39           
     40         If the element is not a member, do nothing. 移除指定元素,不存在不保错 
     41         """
     42         pass
     43   
     44     def intersection(self, *args, **kwargs): # real signature unknown 
     45         """ 
     46         Return the intersection of two sets as a new set. 交集 
     47           
     48         (i.e. all elements that are in both sets.) 
     49         """
     50         pass
     51   
     52     def intersection_update(self, *args, **kwargs): # real signature unknown 
     53         """ Update a set with the intersection of itself and another.  取交集并更更新到A中 """
     54         pass
     55   
     56     def isdisjoint(self, *args, **kwargs): # real signature unknown 
     57         """ Return True if two sets have a null intersection.  如果没有交集,返回True,否则返回False"""
     58         pass
     59   
     60     def issubset(self, *args, **kwargs): # real signature unknown 
     61         """ Report whether another set contains this set.  是否是子序列"""
     62         pass
     63   
     64     def issuperset(self, *args, **kwargs): # real signature unknown 
     65         """ Report whether this set contains another set. 是否是父序列"""
     66         pass
     67   
     68     def pop(self, *args, **kwargs): # real signature unknown 
     69         """ 
     70         Remove and return an arbitrary set element. 
     71         Raises KeyError if the set is empty. 移除元素 
     72         """
     73         pass
     74   
     75     def remove(self, *args, **kwargs): # real signature unknown 
     76         """ 
     77         Remove an element from a set; it must be a member. 
     78           
     79         If the element is not a member, raise a KeyError. 移除指定元素,不存在保错 
     80         """
     81         pass
     82   
     83     def symmetric_difference(self, *args, **kwargs): # real signature unknown 
     84         """ 
     85         Return the symmetric difference of two sets as a new set.  对称差集 
     86           
     87         (i.e. all elements that are in exactly one of the sets.) 
     88         """
     89         pass
     90   
     91     def symmetric_difference_update(self, *args, **kwargs): # real signature unknown 
     92         """ Update a set with the symmetric difference of itself and another. 对称差集,并更新到a中 """
     93         pass
     94   
     95     def union(self, *args, **kwargs): # real signature unknown 
     96         """ 
     97         Return the union of sets as a new set.  并集 
     98           
     99         (i.e. all elements that are in either set.) 
    100         """
    101         pass
    102   
    103     def update(self, *args, **kwargs): # real signature unknown 
    104         """ Update a set with the union of itself and others. 更新 """
    105         pass 

    练习:

    
    
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # Author:wzc

    dic1={
    "a":"8",
    "b":"4",
    "d":"2",
    }

    dic2={
    "a":"4",
    "b":"4",
    "c":"2",
    }

    old_dic=set(dic1)
    print(old_dic)
    new_dic=set(dic2)
    print(new_dic)
    add_key=old_dic.difference(new_dic)
    print(add_key)
    del_key=new_dic.difference(old_dic)
    print(del_key)
    up_key=list(old_dic.intersection(new_dic))
    print(up_key)
    for i in list(up_key):
    #print(dic1[i],dic2[i])
    if dic1[i] != dic2[i]:
    print(i)
    
    

     展示结果:

    {'a', 'd', 'b'}
    {'a', 'c', 'b'}
    {'d'}
    {'c'}
    ['a', 'b']
    a
    

    函数

    定义和使用

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

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

    只被定义的时候,函数体不被执行,只有调用的时候才执行

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # Author:wzc
    def sendmail():
        try:
            import smtplib
            from email.mime.text import MIMEText
            from email.utils import formataddr
    
    
            msg = MIMEText('邮件内容', 'plain', 'utf-8')
            msg['From'] = formataddr(["wpp",'wpp@126.com'])
            msg['To'] = formataddr(["走人",'400000000@qq.com'])
            msg['Subject'] = "主题"
    
            server = smtplib.SMTP("smtp.126.com", 25)
            server.login("wpp@126.com", "密码")
            server.sendmail('wpp@126.com', ['405348163@qq.com',], msg.as_string())
            server.quit()
        except:
            return False
        else:
            return True
    sendmail()
    

    这里面的执行顺序是,先执行def,然后在执行sendmail,然后才是执行函数里面的内容

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # Author:wzc
    def sendmail():
        import smtplib
        from email.mime.text import MIMEText
        from email.utils import formataddr
    
    
        msg = MIMEText('邮件内容', 'plain', 'utf-8')
        msg['From'] = formataddr(["wpp",'wpp@126.com'])
        msg['To'] = formataddr(["走人",'400000000@qq.com'])
        msg['Subject'] = "主题"
    
        server = smtplib.SMTP("smtp.126.com", 25)
        server.login("wpp@126.com", "密码")
        server.sendmail('wpp@126.com', ['405348163@qq.com',], msg.as_string())
        server.quit()
    
    sendmail()
    

    如果try成功了,执行下面的else,如果上面失败了,执行下面的except

    def f1():
            print(123)
            return “123”
    #在函数中,一执行return,后面的就不被执行
            print(456)
    

    参数

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # Author:wzc
    def sendmail():...
    
    
    ret=sendmail('wzc')
    

    def 那行的xxoo就叫做形式参数

    ret那行的参数叫实际参数

    形式参数和实际参数,默认是一一对应的

    def send(xx,oo,xxoo="ok"):
                print(xx,oo,xxoo)
                return Ture
    send("www","haha")
    send("www","haha","nook")    

    默认参数,默认参数必须放到末尾,否则程序异常

    def send(xx,oo):
        print(xx,oo)
    
    send(11,22)
    send(oo="ha",xx="hei")
    

     结果:

    11 22
    hei ha
    

     指定参数

    def f1(*args):
        print(args,type(args))
    
    f1(123,123)
    

     结果:

    (123, 123) <class 'tuple'>
    

    可以传递多个参数

    def f1(*args):
        print(args,type(args))
    li=[11,22,"hah","hh"]
    f1(li)
    f1(*li)
    

     结果:

    ([11, 22, 'hah', 'hh'],) <class 'tuple'>
    (11, 22, 'hah', 'hh') <class 'tuple'>
    

    如果传的值里面有*,就把传的值的每一个元素,都当作元素的每一个元素

    相当做了一个for循环

    带*相当于可以接受动态参数

    def f1(*args):
        print(args,type(args))

    只有*里面获得的参数会变成元组

    def f2(**kwargs):
        print(kwargs,type(kwargs))
    f2(n1="wzc")
    

     结果:

    {'n1': 'wzc'} <class 'dict'>
    

    这里面**变成了字典,传值的时候,必须

    def f2(**kwargs):
        print(kwargs,type(kwargs))
    dic={"k1":"v1","k2":"v2"}
    f2(**dic)
    

     结果:

    {'k2': 'v2', 'k1': 'v1'} <class 'dict'>
    

    会把字典中的每一个元素赋值进去

    万能参数

    def f3(*args,**kwargs):
        print(args,kwargs)
    f3(1,2,34,w=1,z=2,c=3)
    

     结果:

    (1, 2, 34) {'c': 3, 'w': 1, 'z': 2}
    

    自动封装进去

    一定是一个*的在前面,2个* 的在后面

    这就是上面讲到的五种参数

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # Author:wzc
    
    s1="i am {0},age {1}".format("wzc",18)
    print(s1)
    

     结果:

    i am wzc,age 18
    

    {0}和{1}这个叫做站位符

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # Author:wzc
    
    s1="i am {0},age {1}".format("wzc",18)
    print(s1)
    a=["wzc",18]
    s2="i am {0},age {1}".format(*a)
    print(s2)
    

     结果:

    i am wzc,age 18
    i am wzc,age 18
    

    这样传参的时候,必须要写上name和age,这个没有顺序

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # Author:wzc
    
    s1="i am {0},age {1}".format("wzc",18)
    print(s1)
    a=["wzc",18]
    s2="i am {0},age {1}".format(*a)
    print(s2)
    s3="i am {name},age {age}".format(name="wzc",age=18,)
    print(s3)
    dic={
        "name":"wzc",
        "age":18
         }
    s4="i am {name},age {age}".format(**dic)
    print(s4)
    

     结果:

    i am wzc,age 18
    i am wzc,age 18
    i am wzc,age 18
    i am wzc,age 18
    

    python在传参数的时候,是传递参数还是传递引用?

    def f2(a1):
        a1.append(99)
    li=[11,22,33]
    f2(li)
    print(li)
    

     结果:

    [11, 22, 33, 99]
    

    这样就可以确认,在传参数的时候是传一个引用,图2

    def name():
            name="wzc"
            print(name)
    

    作用域,函数只能在作用域里面使用

    全局变量,在所有的作用域都可读

    NAME="wzc"
    def w1():
        print("name:",NAME)
        global NAME
        NAME="www"
    def w2():
        print("name:",NAME)
    print(id(NAME))
    w1()
    print(id(NAME))
    w2()
    

     结果:

    7135728
    name: wzc
    7135952
    name: www
    

    想要对全局变量重新赋值,先使用global

    特殊:列表字典,可修改,不可重新赋值

    全局变量,在定义的时候全部要用大写,潜规则

    三元运算

    红色框是条件

    name="wzc" if 1 == 1 else "niubi"
    print(name)
    

     结果:

    wzc
    

     如果1==1成立,name=wzc,否则name=niubi

    对if 。。。 else的简写

    def f1(a1):
        return (a1+100)
    r1=f1(9)
    print(r1)
    
    f2=lambda a1:a1+100
    r2=f2(10)
    print(r2)
    

     结果:

    109
    110
    

    lambda表达式

    简单的函数

    n1=abs(-1)
    print(n1)
    

     结果:

    1
    
    #0,None,"",[],{}
    #print(bool())
    
    all()
    

     结果:

    Fales
    

    这些的布尔值都是假的

    n2=all([1,2,3,None])
    print(n)
    

     结果:

    Fales
    
    n4=any([1,0,""])
    print(n4)
    

     结果:

    True
    

    只要有真就为真

    print(bin(10))
    print(oct(10))
    print(hex(10))
    

     结果:

    0b1010
    0o12
    0xa

    二进制

    八进制

    十六进制

    ss="王智超"
    nn=bytes(ss,encoding="utf-8")
    print(nn)
    nnq=bytes(ss,encoding="gbk")
    print(nnq)
    

     结果:

    b'xe7x8ex8bxe6x99xbaxe8xb6x85'
    b'xcdxf5xd6xc7xb3xac'
    
    f=open("db.txt","r+",encoding="utf-8")
    # n=f.read()
    # print(n,type(n))
    data=f.read(1)
    print(f.tell())
    f.seek(f.tell())
    f.write("888")
    f.close()
    

     结果:

    1
    

    文件操作

    f=open("db.txt","r+",encoding="utf-8")
    

    python3里面新加的,如果文件存在报错,不存在创建并写内容,和w一样,只能写

    在打开的时候,使用rb就告诉python直接用二进制进行读取。

    f=open("db.txt","rb")
    

    f.seek()主动的把指针调到某个位置,永远是以字节去找位置,不管是不是中文

    print(f.tell())
    

    获取当前指针的位置,永远是字节

    a+,指针永远是在最后面,因为是追加

    w+,先清空,然后才能读写

     2、操作文件

    # read() # 无参数,读全部;有参数,
    #                                    b,按字节
    #                                    无b,按字符
    # tell() 获取当前指针位置(字节)
    # seek(1) 指针跳转到指定位置(字节)
    # write() 写数据,b,字节;无b,字符
    # close
    # fileno
    # flush 强刷
    # readline 仅读取一行
    # truncate 截断,指针为后的清空
    # for循环文件对象 f = open(xxx)
    # for line in f:
    #     print(line)

  • 相关阅读:
    HDOJ 1220 Cube
    LCIS(m*n) 最长公共上升子序列
    第二百九十七天 how can I 坚持
    第二百九十六天 how can I 坚持
    第二百九十五天 how can i 坚持
    第二百九十四天 how can I 坚持
    第二百九十三天 how can I 坚持
    第二百九十、一、二天 how can I 坚持
    第二百八十九天 how can I 坚持
    第二百八十八天 how can I坚持
  • 原文地址:https://www.cnblogs.com/wlzhc/p/5537169.html
Copyright © 2011-2022 走看看