python02

python基础 (v3.6.6)
day02

1. 对象的拷贝

    1-1. 赋值

        list1 = [55,666,9]
        list2 = list1

        #打印变量地址,可以看到结果一样
        print(id(list1))        →: 35575816
        print(id(list2))        →: 35575816

        #修改 list1 后,分别打印list1、list2,结果也一样
        list1.append("tom")

        print(list1)        →: [55, 666, 9, 'tom']
        print(list2)        →: [55, 666, 9, 'tom']

        特点:两个变量都指向同一个对象,其中一个变化时,另一个也跟着变化。

    1-2. 浅拷贝

        list1 = [55,666,[9,30],'tom']
        list2 = list1.copy()

        #打印地址,结果不一样
        print(id(list1))        →: 35770760
        print(id(list2))        →: 35772588

        #修改list1的第一层值,只有list1发生变化(增加了“橘子”)
        list1.append('橘子')
        print(list1)        →: [55, 666, [9, 30], 'tom', '橘子']
        print(list2)        →: [55, 666, [9, 30], 'tom']

        #修改list1的子对象,list1、list2的子对象都发生了变化(增加了“西瓜”)
        list1[2].append('西瓜')
        print(list1)        →: [55, 666, [9, 30, '西瓜'], 'tom', '橘子']
        print(list2)        →: [55, 666, [9, 30, '西瓜'], 'tom']

        特点:两个变量是两个独立的空间,但是他们的子对象还是指向同一个地址


    1-3. 深拷贝

        import copy

        list1 = [55,666,[9,30],'tom']
        list2 = copy.deepcopy(list1)

        #打印地址,结果不一样
        print(id(list1))
        print(id(list2))

        #修改list1的第一层值,只有list1发生变化
        list1.append('橘子')
        print(list1)
        print(list2)


        #修改list1的子对象,还是只有list1发生变化
        list1[2].append('西瓜')
        print(list1)
        print(list2)    

        特点:两个变量是两个独立的空间,他们的子对象也是独立的。

2. 元组 tuple

    元组:元组是以小括号包围,元素以逗号分隔的不可变的序列。

    特点:    a.有序
            b.不可变(不可以对元组内的元素进行增加、单个删除,修改)
            c.可以存储不同的数据类型及结构

    2-1. 定义元组

        tup1 = ()      #空元组
        tup2 = (666,)  #只有一个元素的元组
        tup3 = (666,88)  #多个元素的元组

    2-2. 元组的访问(与字符串、列表一样)

        tup1 = (666,'tom','橘子',[7,'hello'],88)

        print(tup1) #打印整个元组
        
        print(tup1[2])    #下标从0开始  →: 橘子

        print(tup1[3][1])    #嵌套访问  →: hello

        print(tup1[1:3])    #切片访问  →: ('tom', '橘子')

        print(tup1[-2:])    #打印后2位

        print(len(tup1))    #打印元素个数


    2-3. 元组相加

        tup1 = (666,88)
        tup2 = (1,2,3)
        tup3 = tup1 + tup2
        print(tup3)        →: (666, 88, 1, 2, 3)


    2-4. 元组的修改、删除、添加:元组不支持增、删、改

        元组一般存储不变的数据,比如省市区等,
        如果执意修改元组,可以先转化成列表,修改后再转化回元组

    2-5. 元组与列表的转化
        tup1 = (666,88)
        list1 = list(tup1)    #元组转化成列表

        tup2 = tuple(list1)    #列表转化成元组


3. if判断

    ① if语句
    if 条件:
        满足条件执行的语句

    ② if-else
    if 条件1:
        满足条件1执行的语句
    else:
        不满足条件1执行的语句

    ③ if-elif-else
    if 条件1:
        满足条件1执行的语句
    elif 条件2:
        满足条件2执行的语句
    elif 条件n:
        满足条件n执行的语句
    else:
        不满足上述条件执行的语句

4. Python的真假
    1).任何非零和非空对象都为真 解释为True
    2).数字0、空对象和特殊对象None均为假 解释为False    

    组合条件测试
    X and Y: 与运算
    X or  Y: 或运算
    not   X: 非运算

    1) and的优先级大于or
    2) and连接的两个条件都满足,才成立
    3) or连接的两个条件有一个满足,即成立

5. while循环

    while 条件:
        满足条件执行的循环体

    注意:while循环是每次循环结束后,会再次检查条件是否满足;
        使用循环时,要对循环条件加以控制,否则会进入死循环。

        while 条件:
            满足条件执行的循环体
            循环结束控制语句        


     break:终止循环(当前层次的循环)
     continue:跳出本次循环(continue后面的代码是不执行的),开始下次循环

     注:break、continue只用在while、for循环中


6. for循环语句
    
    for 变量 in 集合:
        集合内依次取值,执行满足条件的循环体

    for循环的次数由集合的个数决定

    for循环可以遍历字符串、列表、元组等

7. range函数
    range(m,n,t) 表示连续的整数范围,m为起始值,n-1为结束值,t为步长,步长为1时可省略

    range(1,5) →:1,2,3,4
    range(1,5,2) →:1,3
    range(5)   →:0,1,2,3,4

8. 列表推导式

    语法1: lst= [ele  for  ele  in 范围 if 条件]
    语法2: lst= [ele  if 条件 else  ele  for  ele  in 范围]

    list1 = [i for i in range(1,11) ]
    print(list1)    →: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

    list2 = [j for j in range(1,11) if j % 2 == 0 ]
    print(list2)    →: [2, 4, 6, 8, 10]

        补充(了解):
        vec = [2, 4, 6]
        list3 = [3*m for m in vec]
        print(list3)    →: [6, 12, 18]

        list4 = [3*k for k in vec if k > 3]
        print(list4)    →: [12, 18]

        list5 = [3*t if t > 3 else 100*t for t in vec ]
        print(list5)    →: [200, 12, 18]


        vec1 = [1, 2, 3]
        vec2 = [4, 5, ]
        list6 = [x*y for x in vec1 for y in vec2]
        print(list6)    →: [4, 5, 8, 10, 12, 15]


    练习2:有个包含0和1的字符串,求出连续的0或连续的1的最大值
        str1 = '11111111110010000000000001111011'
        # print(str1.split('1'))
        list1 = []
        for i in str1.split('1'):   #指定字符串切割
            list1.append(len(i))
            # print(list1)  #打印每个元素的长度
        print("连续的0最大值是",max(list1))

        #方法2
        str1 = '11111111110010000000000001111011'
        # print(str1.split('1'))
        max1 = max([len(i) for i in str1.split('0')])
        print("连续的1的最大值是",max1)

        max0 = max(len(j) for j in str1.split('1'))
        print("连续的0的最大值是{}".format(max0))
        print(f"连续的0的最大值是{max0}")

    #练习3:s = '2020 8 11 23 5 59 8 6 999',将s变成'202008112305590806999',
         即不足2位的补0,最终连起来

        s = '2020 8 11 23 5 59 8 6 999'
        list0 = []
        for i in s.split(" "):
            if len(i) < 2:
                list0.append("0" + i)
            else:
                list0.append(i)
        # print(list0)
        s1 = "".join(list0)
        print(s1)

        #方法2,列表推导式
        s = '2020 8 11 23 5 59 8 6 999'
        s2= "".join(["0" + i if len(i) <2 else i for i in s.split(" ")])
        print(s2)


9. 二次循环嵌套

    #练习1:九九乘法口诀表

        for i in range(1,10):
            for j in range(1,i+1):
                print("%d*%d=%d"%(j,i,j*i),end = "\t")
            print()

    #练习2.冒泡排序:列表lst = [3,8,2,12,56,9],把列表中的数据由高到低排序。

        lst = [3,8,2,12,56,9]
        num = len(lst)
        for i in range(num-1):   # 外层循环控制对比轮次
            for j in range(num-i-1):  # 内层循环表示每轮的对比次数
                if lst[j] < lst[j+1]:
                    lst[j],lst[j+1] = lst[j+1],lst[j]
        print(lst)    

10. 字典 dict

    字典是python中的一个映射的数据类型,他是一种一一对应的关系,使用{}表示。
    字典由多个键:值对组成,中间的每一项用逗号分割开,键必须唯一,值可以重复。
    字典的元素(键值对)是无序的,不支持索引取值。

    字典特点
        1)字典的键是唯一的,不可变,但值不必是唯一的
        2)当字典中有重复键产生的时候,字典会保留最后一个
        3)字典的键值对是无序的,字典的值只能通过对应的键来访问

    dict2 = {'name':'tom','age':20} 
    name是键,即key,tom是值,即value

    10-1. 定义字典

        dict1 = {} #定义空字典

        dict2 = {'name':'tom','age':20} #定义非空字典

    10-2. 访问字典

        print(dict2)  #访问字典

        #获取指定键的值
        print(dict2['name'])    

        #使用get方法获取指定键的值
        print(dict2.get('age')) 

        #两种获取的区别:如果不小心输错键,中括号会报错,get会直接返回None,不报错。


        #获取字典的所有键
        print(dict2.keys())            :→ dict_keys(['name', 'age'])

        #将所有的key转化成列表
        print(type(dict2.keys()))    :→ <class 'dict_keys'>
        print(list(dict2.keys()))    :→ ['name', 'age']


        #获取字典的所有值
        print(dict2.values())     


        #获取字典的所有键值对
        print(dict2.items())

            for i in dict2.items():   #使用for循环遍历键值对
                print(i)
            for k,v in dict2.items(): #使用for循环分别遍历键和值
                print(k,v)
                print(k)        

        print(dir(变量))       #查看变量的内置方法,变量可以是字典、集合等等

    10-3. 根据value的值,来获取key

        练习:有一个字典 {'key1':'a', 'key2':'b','key3':'c'},请输出值b对应的key

            #方法一:使用for循环
            dict3 = {'key1':'a', 'key2':'b','key3':'c'}
            for k in dict3.keys():
                if dict3.get(k) ==  'b':
                    print("b对应的key是:",k)

            #方法二:使用列表[下标],即先转成列表,再索引取值
            print(list(dict3.keys())[list(dict3.values()).index("b")])

    10-4. 字典推导式

        语法1:dict = {key:value for key,value in dict.items() if 条件}
        语法2:dict = {key:value if 条件 k,v  else k,v for  key,value in dict.items()}


        #例题:有一个字典{"数学":89,"英语":70,"物理":90,"化学":78},获取分数最高的学科
 
            #方法一,使用字典推导式
            dict5 = {"数学":89,"英语":70,"物理":90,"化学":78}
            dict6 = {k:v for k,v in dict5.items() if v == max(list(dict5.values()))}
            print(dict6)

            #方法二,使用for循环
            dict5 = {"数学":89,"英语":70,"物理":90,"化学":78}
            dict7 = {}
            for k,v in dict5.items():
                if v == max(list(dict5.values())):
                    dict7[k] = v
            print(dict7)

        #字典的values也可以用max()函数求最大值
            dict5 = {"数学":89,"英语":70,"物理":90,"化学":78}
            print(max(dict5.values()))        :→ 90

    10-5. 判断键是否存在(只能判断键)

        dict2 = {'name':'tom','age':20}
        print("name" in dict2)    :→ True

    10-6. 增加字典的值

        dict2["sex"] = "男"
        print(dict2)    →: {'name': 'tom', 'age': 20, 'sex': '男'}

    10-7. 修改字典的值
    
        dict2["name"] = "xiaoming"
        print(dict2)    →: {'name': 'xiaoming', 'age': 20, 'sex': '男'}            

    10-8. 设置字典的默认值

        dict2 = {"name":"tom","age":20}
        dict2.setdefault("sex","男")
        print(dict2)    →: {'name': 'tom', 'age': 20, 'sex': '男'}

        #注意:字典的默认值,不会更新原来的值,只能设置原来不存在的键的值
        dict2.setdefault("age",66)
        print(dict2)    →:     {'name': 'tom', 'age': 20, 'sex': '男'}


            了解:

            #get()做的默认值操作是不能给字典赋值的,只是作为取数据的默认值操作
            dict3 = {}
            dict3.get("name","lily")
            print(dict3)    →: {}
            print(dict3.get("name","lily"))    →: lily
            print(dict3)    →: {}

    10-9. 合并两个字典

        dict1 = {"sex":"男"}
        dict2 = {"name":"tom","age":20}

        #将dict2合并到dict1里面
        dict1.update(dict2)
        print(dict1)    →: {'sex': '男', 'name': 'tom', 'age': 20}

        #将dict1合并到dict2里面
        dict2.update(dict1)
        print(dict2)    →: {'name': 'tom', 'age': 20, 'sex': '男'}

        #将dict4合并到dict3里面,key相同,dict4的值会覆盖dict3
        dict3 = {"name":"小明"}
        dict4 = {"name":"tom","age":20}

        dict3.update(dict4)
        print(dict3)    →: {'name': 'tom', 'age': 20}

    10-10. 统计字典个数(键值对的数量)

        dict3 = {"name":"小明","sex":"男"}
        print(len(dict3))    →: 2


    10-11. 删除字典元素

        #删除指定键 del
        dict3 = {"name":"小明","sex":"男","age":20}
        del dict3["age"]
        print(dict3)    →: {'name': '小明', 'sex': '男'}

        #删除指定键 pop()方法会返回结果
        dict4 = {"name":"小明","sex":"男","age":20}
        a = dict4.pop("name")
        print(a)        →: 小明
        print(dict4)    →: {'name': '小明', 'sex': '男'}


        #清空字典 clear()
        dict5 = {"name":"小明","sex":"男","age":20}
        dict5.clear()
        print(dict5)    →: {}

        #删除整个字典 del
        dict6 = {"name":"小明","sex":"男","age":20}
        del dict6
        print(dict6)    →: 报错


11. 补充:字典和列表的嵌套访问

    list1 = [20,'橘子',{'name':'tom','age':20},666]
    print(list1[2])          #打印出列表中的字典
    print(list1[2]['name'])  #获取字典中name的值
    print(list1[2].get('age'))

    #多层嵌套(列表套字典)
    list1 = [[20,'橘子'],20,[{'name':'tom','age':20},5],666]
    print(list1[2][0]['name'])              →:tom
    print(list1[2][0].get('age'))           →:20

    #多层嵌套(字典套列表,列表再套字典)
    list1 ={'stu':[[20,'橘子'],20,[{'name':'tom','age':20},5],666],'num':999}
    print(list1['stu'][0][1])               →:橘子
    print(list1['stu'][2][0].get('age'))    →:20


12. 集合 set

    集合是一个无序、不重复元素的序列,不支持索引取值。使用 { } 或者 set() 创建集合。

    注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。


    12-1. 定义集合

        定义空集合
        set1 = set()

        定义非空集合
        set2 = {'西瓜',666,'橘子',(55,888),100}

        注意:集合里面可以嵌套元组,但是不能嵌套字典、列表。

    12-2. 添加集合的元素
        set2.add("tom")


    12-3. 删除集合中的元素

        set2.pop()            #随机删除一个元素

        set2.remove('橘子')    #删除指定元素

    12-4. 统计集合中元素的个数

        print(len(set2))

    12-5. 判断元素是否在集合中存在

        print("西瓜" in set2)


    12-6. 集合的键是唯一的,自动过滤重复的键(可以对列表去重)

        list1 = [1,2,3,3,666,888,666]
        set1 = set(list1)
        print(set1)        →: {1, 2, 3, 888, 666}

    12-7. 集合的访问(不支持索引访问)

        print(set2[1])     →: 报错

    12-8. 集合推导式

        语法: { i for i in 范围 if条件 }

        例题:获取1到10的偶数,并加入到集合中

            #方法一,使用for循环
            set1 = set()
            for i in range(1,11):
                if i % 2 == 0:
                    set1.add(i)
            print(set1)

            #方法二,使用集合推导式
            set2 = {a for a in range(1,11) if a%2==0}
            print(set2)
            

13. 第二天课后练习

    #练习1:请用你所熟悉的程序语言实现求一个整数数组里面两个数之和为183的所有整数对
            #(例如:输入数组为[183,0,1,2,-184,367],得到结果为{(183,0),(-184,367)})

            list1 = [183,0,1,2,-184,367]
            set1 = set()
            #外层循环,获取需要和后面的值相加的下标对应的值
            for i in range(len(list1)-1):
                #内层循环,控制循环的次数,当i增加,内层循环相应减少
                for j in range(i+1,len(list1)):
                    if list1[i] + list1[j] == 183:
                        # print(list1[i],list1[j])
                        #集合嵌套元组的形式保存结果
                        set1.add((list1[i],list1[j]))
            print(set1)


    #练习2: 1到9999中,包含数字2的数字共有多少个?

            total = 0
            for i in range(10000):
                if '2' in str(i):
                    total+=1
            print(total)


    #练习3:给定一个只包含正整数且非空的数组,返回该数组中重复次数最多的前N个数字(返回结果
            # 按重复次数从大到小降序排列,N不存在取值非法的情况 ),试用代码实现该需求

            list1 = [5,2,5,6,9,8,7,2,1,5,6,2,4,5,8,2,1,2,6]
            #统计每个元素的次数,并构造成字典
            dict1 = {i:list1.count(i) for i in list1}
            #print(dict1)    →: {5: 4, 2: 5, 6: 3, 9: 1, 8: 2, 7: 1, 1: 2, 4: 1}
            #将每个键值对转化成列表
            list2 = []
            for k,v in dict1.items():
                list2.append({k:v})
            #print(list2)    →: [{5: 4}, {2: 5}, {6: 3}, {9: 1}, {8: 2}, {7: 1}, {1: 2}, {4: 1}]
            #按元素出现次数由大到小排列(冒泡排序)
            for i in range(len(list2)-1):
                for j in range(len(list2)-i-1):
                    if list(list2[j].values())[0] < list(list2[j+1].values())[0]:
                        list2[j],list2[j+1] = list2[j+1],list2[j]
            #print(list2)    →: [{2: 5}, {5: 4}, {6: 3}, {8: 2}, {1: 2}, {9: 1}, {7: 1}, {4: 1}]
            #取前N个(比如3个)
            print(list2[:3])    →: [{2: 5}, {5: 4}, {6: 3}]


    #补充练习:给定一个字符串,找出该字符串中出现次数最多的那个字符,并打印出该字符及次数
            #如 输入 aaaabbc,输出 a:4

            a = 'aaaabbc'
            dict1 = {s:a.count(s) for s in set(a)}
            # print(dict1)            # →: {'a': 4, 'c': 1, 'b': 2}
            dict2 = {k:v for k,v in dict1.items() if v == max(dict1.values())}
            # print(dict2)            # →: {'a': 4}
            for k,v in dict2.items():
                print(k+":"+str(v))    # →: a:4


    类似for循环里面有if条件判断的,都可以试着使用推导式(列表、字典、集合)
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值