zoukankan      html  css  js  c++  java
  • python自动化运维之路2

    list列表

    列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作

    #!/usr/bin/env python 
    # _*_ encoding:utf-8 _*_
    # author:snate
    name_list = ["alex","zhangdan","daxiaowen","jack"]
    print(name_list[0])
    print(name_list[1:3])  # 切片 左闭右开  顾头不顾尾
    print(name_list[0:3])
    print(name_list[-1])
    print(name_list[-2:-1])  # ['daxiaowen']
    print(name_list[0:-1]) # ['alex', 'zhangdan', 'daxiaowen']
    print(name_list[0:3:2])# ['alex', 'daxiaowen']
    print(name_list.index("daxiaowen"))  # 2 查找某个元素所在的下标
    name_list.append("gxw")   # 在末尾添加一个元素
    name_list.insert(2,"nihao") # 在2的位置插入nihao
    
    name_list[2]="张丹" # 修改元素的值
    
    print(name_list)
    name_list.append("daxiaowen")
    print(name_list.count("daxiaowen"))  # 统计某个字符串出现的次数
    print(len(name_list))  # 用函数len统计字符串的长度
    print(name_list)
    del name_list[2] # 删除第三个元素
    print(name_list)
    # del name_list  # 删除整个列表 print(name_list)
    if "daxiaowen" in name_list: # 判断某个元素是否在列表中
        print(name_list.index("daxiaowen"))
    for i in name_list:   # 遍历整理列表,
        print(i)
    for index,element in enumerate(name_list): # 遍历整个列表,下标一块打印,使用enumerate函数
        print(index, element)

    list对象的赋值、浅copy 和深copy

    will = ["Will", 28, ["Python", "C#", "JavaScript"]]
    wilber = will
    print id(will)
    print will
    print [id(ele) for ele in will]
    print id(wilber)
    print wilber
    print [id(ele) for ele in wilber]
    will[0] = "Wilber"
    will[2].append("CSS")
    print id(will)
    print will
    print [id(ele) for ele in will]
    print id(wilber)
    print wilber
    print [id(ele) for ele in wilber]

    执行结果:

    分析:

    首先,创建了一个名为will的变量,这个变量指向一个list对象,从第一张图中可以看到所有对象的地址(每次运行,结果可能不同)
    然后,通过will变量对wilber变量进行赋值,那么wilber变量将指向will变量对应的对象(内存地址),也就是说”wilber is will”,”wilber[i] is will[i]”
    可以理解为,Python中,对象的赋值都是进行对象引用(内存地址)传递
    第三张图中,由于will和wilber指向同一个对象,所以对will的任何修改都会体现在wilber上
    这里需要注意的一点是,str是不可变类型,所以当修改的时候会替换旧的对象,产生一个新的地址39758496

    浅copy

    import copy
    will = ["Will", 28, ["Python", "C#", "JavaScript"]]
    wilber = copy.copy(will)
    
    print id(will)
    print will
    print [id(ele) for ele in will]
    print id(wilber)
    print wilber
    print [id(ele) for ele in wilber]
    
    will[0] = "Wilber"
    will[2].append("CSS")
    print id(will)
    print will
    print [id(ele) for ele in will]
    print id(wilber)
    print wilber
    print [id(ele) for ele in wilber]
    

      执行结果:

    分析:

    首先,依然使用一个will变量,指向一个list类型的对象
    然后,通过copy模块里面的浅拷贝函数copy(),对will指向的对象进行浅拷贝,然后浅拷贝生成的新对象赋值给wilber变量
    浅拷贝会创建一个新的对象,这个例子中”wilber is not will”
    但是,对于对象中的元素,浅拷贝就只会使用原始元素的引用(内存地址),也就是说”wilber[i] is will[i]”

    当对will进行修改的时候
    由于list的第一个元素是不可变类型,所以will对应的list的第一个元素会使用一个新的对象39758496
    但是list的第三个元素是一个可变类型,修改操作不会产生新的对象,所以will的修改结果会相应的反应到wilber上

    备注:使用下面的操作会产生浅copy的效果
    使用切片[:]操作
    使用工厂函数(如list/dir/set)
    使用copy模块中的copy()函数

    深copy

    import copy
    
    will = ["Will", 28, ["Python", "C#", "JavaScript"]]
    wilber = copy.deepcopy(will)
    
    print id(will)
    print will
    print [id(ele) for ele in will]
    print id(wilber)
    print wilber
    print [id(ele) for ele in wilber]
    
    will[0] = "Wilber"
    will[2].append("CSS")
    print id(will)
    print will
    print [id(ele) for ele in will]
    print id(wilber)
    print wilber
    print [id(ele) for ele in wilber]

    分析:

    首先,同样使用一个will变量,指向一个list类型的对象
    然后,通过copy模块里面的深拷贝函数deepcopy(),对will指向的对象进行深拷贝,然后深拷贝生成的新对象赋值给wilber变量
    跟浅拷贝类似,深拷贝也会创建一个新的对象,这个例子中”wilber is not will”
    但是,对于对象中的元素,深拷贝都会重新生成一份(有特殊情况,下面会说明),而不是简单的使用原始元素的引用(内存地址)
    例子中will的第三个元素指向39737304,而wilber的第三个元素是一个全新的对象39773088,也就是说,”wilber[2] is not will[2]”

    当对will进行修改的时候
    由于list的第一个元素是不可变类型,所以will对应的list的第一个元素会使用一个新的对象39758496
    但是list的第三个元素是一个可不类型,修改操作不会产生新的对象,但是由于”wilber[2] is not will[2]”,所以will的修改不会影响wilber

    购物车:

    ReadME:

    这个一个关于购物车的程序
    个人介绍
    name:Gaoxuewu
    nickName:snate
    blog_addr:http://www.cnblogs.com/itlinux/p/5723060.html
    功能介绍
    fullShopping.py
    输入用户名,登录到电子商城,判断用户名在用户文件中是否存在,存在读取用户工资,若不存在将完成购物, 退出系统时,将用户的信息写入到 用户文件中。
    用户可以完成购物、修改购物车信息(添加和删除购物车的商品)、结账退出等操作。
    从文件中读取商品的种类和价格信息。
    将购物车信息写入到文件中。
    Manger.py
    从文件中读取商品信息保存到字典中。
    修改商品的价格,并写回文件
    环境依赖
    python3.*
    window/linux os
    time
    目录结构
    fullShopping
    ├── __init__.py
    ├── README.md # 程序介绍
    ├── fullShopping flowChart # 程序流程图
    ├── user.txt # 用户信息,包含用户名和用户的余额信息
    ├── Product_list.txt  # 商品信息,包含商品的编号,商品名称和价格
    ├── Shopping_list.txt # 购物车信息 包含商品的名称,购物商品的数量
    ├── fullShopping.py # 电子商城测试程序
          ├── ReadProductDic() # 将商品信息从文件中读取,并保存到字典中
          ├── WriteShoppingProductFile(Shopping_Chart) # 将购买的商品以及商品的数量写入到文件中
          ├── Exit_System() # 退出系统
          ├── BreakFlag() # 判断是否需要继续
          ├── ThroughProductDic(Product_list) #  遍历商品列表
          ├── ThroughShoppingDic(Shopping_Chart) # 遍历购物车字典
    ├── Manager.py # 管理员程序
          ├── ReadProductDic()  # 读取商品信息到文件
          ├── ThroughShoppingDic(Shopping_Chart) # 保存商品信息到文件
    运行说明
    用户程序
    将文件拷贝到安装好python3.*的系统环境中,执行python fullShopping.py即可。
    管理员程序
    将文件拷贝到安装好python3.*的系统环境中,执行python Manger.py即可。
    

    流程图:购物车流程图:

    购物车1:

    购物车购物、修改购物车、结账退出。

    #!/usr/bin/env python 
    # _*_ encoding:utf-8 _*_
    # author:snate
    product_list =[("MyWatch",8000),
                   ("NoteBook",3000),
                   ("xiaoMiPhone",1500),
                   ("apple",5)
                   ]
    shopping_list=[]
    salary =int(input("请输入您的工资:"))
    print("==========product list=============")
    while True:
        for index,product in enumerate(product_list):
            print(index,product_list[index][0],product_list[index][1])
        user_choice = input("请输入您的选择:")
        if user_choice.isdigit():
            user_choice = int(user_choice)
            if user_choice >=0 and user_choice <len(product_list):
                if product_list[user_choice][1]<salary:
                    product = product_list[user_choice]
                    salary -= product[1]
                    shopping_list.append(product[0])
                    print("added the \033[31;1m%s \033[0m to shopping chart!,your salary is \033[31;1m%s \033[0m" %(product[0],salary))
                else:
                    print("您的余额为: \033[42;1m%s \033[0m,不足以支出此产品,买个毛线呀!" %salary)
            else:
                print("您输入编号为\033[41;1m%s] \033[0的商品不存在,请重新输入"% user_choice)
        elif user_choice == "q":
            print("============shopping list=====================")
            for product in shopping_list:
                print(product)
            print("您的余额为:\033[42;1m%s \033[0m"% salary)
            exit()
        else:
            print("invalid option")
    

      购物车2:

    #!/usr/bin/env python 
    # _*_ encoding:utf-8 _*_
    # author:snate
    def print_menu_table(): #  打印商品列表的表头
        print("===========商品清单为:===================")
        menu_table = '''
                    编号    商品名称       商品价格
              '''
        print(menu_table)
    def print_menu_list(menu_list): #  打印商品列表
         print_menu_table()
         for index,item in enumerate(menu_list):
            menu_dic[index] = menu_list[index];
            menu_info='''
                    {id}      {name}       {price}
            '''.format(id=index,name=menu_list[index][0],price=menu_list[index][1])
            print(menu_info)
    # 购物,并且将购买的商品加入到字典中,其中关键字商品的名称及单价,value值为cnt
    def shopping():
        your_balance=int(input("请输入您的工资:"))
        while True:
            print_menu_list(menu_list)
            cnt = 0;#记录商品的数量
            user_choice = input("请输入您的商品编号:")
            if user_choice.isdigit():
                user_choice = int(user_choice)
                if user_choice >=0  and  user_choice < len(menu_list):
                    if menu_list[user_choice][1] < your_balance:
                        shopping_product = menu_list[user_choice]
                        if shopping_product in shopping_dic:
                            shopping_dic[shopping_product] += 1
                            your_balance -= shopping_product[1]
                        else:
                            shopping_dic[shopping_product] = 1
                            your_balance -= shopping_product[1]
                        print("将商品[%s]加入到购物车,您的余额为:%s" % (shopping_product[0], your_balance))
                    else:
                        print("您的余额为\033[31;1m%s\033[0m,不足以支出次商品,还买个屁呀!" % your_balance)
                else:
                    print("您输入\033[31;1m[%s]\033[0m不存在,请输入输入!" % user_choice)
            elif user_choice == "q":
                print("=============shopping list===============")
                print_shopping_list(shopping_dic)
                print("您的余额为:\033[31;1m[%s]\033[0m!" %your_balance)
                exit()
            else:
                print("invalid option")
    # 购物,并且将购买的商品加入到字典中,其中关键字商品的名称及单价,value值为cnt
    def print_shopping_list(shopping_dic):
        print("\t\t商品编号\t\t商品名称\t\t商品价格\t\t商品数量");
        for index,product in enumerate(shopping_dic):
            print("\t\t%s\t\t%s\t\t%s\t\t%s"% (index, product[0], product[1], shopping_dic[product]))
    
    menu_list = [("ihone", 3800), ("notebook", 800), ("pen", 50), ("apple", 30)]
    if __name__ == '__main__':
        menu_dic = {}
        shopping_dic = {}
        shopping()
        print_shopping_list(shopping_dic)
    

      购物车3:

    #!/usr/bin/env python 
    # _*_ encoding:utf-8 _*_
    # author:snate
    import time
    # 将商品列表从文件中读出,并写入字典
    def ReadProductDic():
        with open('Product_List.txt', 'r', encoding="utf-8") as f:
            for line in f.readlines():
                Product_Info = line.strip("\n").split(" ")
                # Index = int(Product_Info[0])
                Product_Name = Product_Info[1]
                Product_Price = Product_Info[2]
                Product_List[Product_Name] = int(Product_Price)
    # 将购买的商品以及商品的数量写入到文件中
    def WriteShoppingProductFile(Shopping_Chart):
        with open('Shopping_list.txt', 'a', encoding="utf-8") as f:
            for index,Proudct_Name in enumerate(Shopping_Chart):
                Product_Str=""
                index = str(index)
                Prduct_Num = str(Shopping_Chart[Product_Name])
                Product_Str= Product_Str+index + " " + Product_Name + " "+ Prduct_Num
                f.writelines(Product_Str+"\n")
    # 退出系统
    def Exit_System():
        for i in  range(3):
            print('''\n\t\t谢谢使用电子购物商城,\033[34;1m%s\033[0m秒后,退出系统!''' %(3-i))
            time.sleep(1)
        exit()
    # 判断是否需要继续
    def BreakFlag():
        while True:
            Break_Flag = input('''\t\t您是否要继续?(y/n)''')
            if  Break_Flag =="y" or Break_Flag == "n":
                return Break_Flag
            else:
                print("您的输入有误,请重新输入")
    # 遍历 商品字典 输入商品编号,商品的名称 商品的价格
    def ThroughProductDic(Product_list):
        for index, Product in enumerate(Product_list):
            Dic_key[index] = Product
            print(index,Product,Product_List[Product])
    #   遍历购物车字典,打印序号、商品名称、商品的单价、商品的数量
    def ThroughShoppingDic(Shopping_Chart):
        for index,name in enumerate(Shopping_Chart):
            Dic_key[index] = name
            print('''\n\t\t%s\t\t%s\t\t%s\t\t%s\t\t''' %(index,name,Product_List[name],Shopping_Chart[name]))
    Dic_key = {}
    Shopping_Chart = {}  # 保存购买的商品
    # 商品列表
    Product_List={}
    ReadProductDic()
    # 判断工资标准
    name=input('请输入您的用户名:')
    print('''\n\t\t\t\t\033[31;5m欢迎%s来到电子商城\033[0m''' %name)
    with open("user.txt",'r+',encoding='utf-8') as f:
        count = f.readlines().count(name)
        cnt = 0
        for line in f.readlines():
            line = line.strip("\n").split(" ")
            # 文件中可能存在多个用户的余额信息,选取最后的余额
            if name == line[1]:
                cnt += 1
                if cnt == count:
                    balance = line[2]
                    break
        else:
            Balance = input("请输入您的工资:")
            Balance = int(Balance)
    while True:
        Break_Flag =''
        print('''\n\t请选择您需要进行的操作:\n\t\t\t\t1.购物\n\t\t\t\t2.查看并修改购物车\n\t\t\t\t3.结账并退出''')
        # 用来确定用户的选择
        while True:
            choose = input('''\n\t请输入您的选择''')
            if choose.isdigit():
                choose = int(choose)
                if choose >=4 or choose <= 0:
                    print('''\n\t\t您的输入有误,请重新输入,谢谢!''')
                else:
                    break
            elif choose == "q":
                print('''\n\t\t序号\t\tname\t\tprice\t\tnum\t\t''')
                ThroughShoppingDic(Shopping_Chart)
                WriteShoppingProductFile(Shopping_Chart)
                print('''您的余额为:%s''' % Balance)
                Exit_System()
            else:
                print("invalid option")
        # 用户的选择为1,购物
        if choose == 1:
            while Break_Flag != 'n':
                ThroughProductDic(Product_List)
                User_Choose = input('''\t\t请输入您要购买的商品的编号:''')
                if User_Choose.isdigit():
                    User_Choose = int(User_Choose)
                    if User_Choose >=0 and User_Choose<len(Dic_key):
                        Product_Name = Dic_key[User_Choose]
                        if Product_List[Product_Name]< Balance:
                            Balance -= Product_List[Product_Name]
                            print('''\t\t将商品\033[31;1m[%s]\033[0m加入到购物车!''' %Product_Name)
                            # 判断商品是否在购物车中,如果在购物车中的数量加1,若果不在购物车中,
                            if Product_Name in Shopping_Chart:
                                Shopping_Chart[Product_Name] += 1
                            else:
                                Shopping_Chart[Product_Name] =1
                        else:
                            print('''\t\t您的余额不足,请重新输入!''')
                    else:
                        print('''\t\t您输入的编号为\033[31;1m%s]\033[0m不存在'''% User_Choose)
                elif User_Choose == 'q':
                    print('''\n\t\t序号\t\tname\t\tprice\t\tnum\t\t''')
                    ThroughShoppingDic(Shopping_Chart)
                    WriteShoppingProductFile(Shopping_Chart)
                    print('''您的余额为:%s''' % Balance)
                    with open("user.txt", 'r+', encoding='utf-8') as f:
                        User_Info = name+ ""+str(Balance)
                        f.writelines(User_Info+"\n")
                    Exit_System()
                else:
                    print("invalid option")
                Break_Flag = BreakFlag()
    
        elif  choose == 2:
            while True:
                ThroughShoppingDic(Shopping_Chart)
                Shopping_Chart_Choose = input('''\t\t1.增加\n\t\t2.删除\n\t\t3.结账并退出\n\t\t4.返回\n\t\t请输入您的选择:''')
                if Shopping_Chart_Choose.isdigit():
                    Shopping_Chart_Choose = int(Shopping_Chart_Choose)
                    if Shopping_Chart_Choose<=0 or Shopping_Chart_Choose >= 5:
                        print('''您输入编号为[%s]的操作不存在,请您重新输入!''' % Shopping_Chart_Choose)
                    else:
                        break
                elif  Shopping_Chart_Choose=="q":
                    print('''\n\t\t序号\t\tname\t\tprice\t\tnum\t\t''')
                    ThroughShoppingDic(Shopping_Chart)
                    WriteShoppingProductFile(Shopping_Chart)
                    print('''您的余额为:%s''' % Balance)
                    with open("user.txt", 'r+', encoding='utf-8') as f:
    
                        User_Info = name + "" + str(Balance)
                        f.writelines(User_Info + "\n")
                    Exit_System()
                else:
                    print("您的输入有误,请重新输入")
            if Shopping_Chart_Choose == 1:
                while  Break_Flag != 'n':
                    ThroughShoppingDic(Shopping_Chart)
                    Add_Shoppping_Index = input('''\n\t\t请输入您要增加商品的编号:''')
                    if Add_Shoppping_Index.isdigit():
                        Add_Shoppping_Index = int(Add_Shoppping_Index)
                        if Add_Shoppping_Index>= 0 and Add_Shoppping_Index<len(Shopping_Chart):
                            Add_Product_Name = Dic_key[Add_Shoppping_Index]
                            while Break_Flag != 'n':
                                Add_Product_Num = input('''\t\t请输入您要增加的商品数量:''')
                                if Add_Product_Num.isdigit():
                                    Add_Product_Num = int(Add_Product_Num)
                                    if Balance >= Product_List[Add_Product_Name]*Add_Product_Num:
                                        Shopping_Chart[Add_Product_Name] += Add_Product_Num
                                        Balance -= Product_List[Add_Product_Name]*Add_Product_Num
                                    else:
                                        print('''\t\t您的余额不足!''')
                                elif Add_Product_Num == "q":
                                    print('''\n\t\t序号\t\tname\t\tprice\t\tnum\t\t''')
                                    ThroughShoppingDic(Shopping_Chart)
                                    WriteShoppingProductFile(Shopping_Chart)
                                    print('''您的余额为:%s''' % Balance)
                                    Exit_System()
                                else:
                                    print('invalid option')
                                Break_Flag = BreakFlag()
                        else:
                            print('''您输入编号为[%s]的操作不存在!''' % Shopping_Chart_Choose)
                    elif Add_Shoppping_Index == 'q':
                        print('''\n\t\t序号\t\tname\t\tprice\t\tnum\t\t''')
                        ThroughShoppingDic(Shopping_Chart)
                        WriteShoppingProductFile(Shopping_Chart)
                        print('''您的余额为:%s''' % Balance)
                        with open("user.txt", 'r+', encoding='utf-8') as f:
                            User_Info = name + "" + str(Balance)
                            f.writelines(User_Info + "\n")
                        Exit_System()
                    else:
                        print("invalid option")
                    Break_Flag = BreakFlag()
            elif Shopping_Chart_Choose==2:
                while Break_Flag != 'n':
                    ThroughShoppingDic(Shopping_Chart)
                    Del_Shoppping_Index = input('''\n\t\t请输入您要删除商品的编号:''')
                    if Del_Shoppping_Index.isdigit():
                        Del_Shoppping_Index = int(Del_Shoppping_Index)
                        if Del_Shoppping_Index >= 0 and Del_Shoppping_Index < len(Shopping_Chart):
                            Del_Product_Name = Dic_key[Del_Shoppping_Index]
                            while Break_Flag != 'n':
                                Del_Product_Num = input('''\t\t请输入您要增加的商品数量:''')
                                if Del_Product_Num.isdigit():
                                    Del_Product_Num = int(Del_Product_Num)
                                    if Del_Product_Num>=0 and Del_Product_Num<=Shopping_Chart[Del_Product_Name]:
                                        Balance += Product_List[Del_Product_Name]*Del_Product_Num
                                    else:
                                        print('''\t\t您输入的商品数量有误,请重新输入!''')
                                elif Add_Product_Num == "q":
                                    print('''\n\t\t序号\t\tname\t\tprice\t\tnum\t\t''')
                                    ThroughShoppingDic(Shopping_Chart)
                                    WriteShoppingProductFile(Shopping_Chart)
                                    print('''您的余额为:%s''' % Balance)
                                    with open("user.txt", 'r+', encoding='utf-8') as f:
                                        User_Info = name + "" + str(Balance)
                                        f.writelines(User_Info + "\n")
                                    Exit_System()
                                else:
                                    print('invalid option')
                                Break_Flag = BreakFlag()
                        else:
                            print('''您输入编号为[%s]的操作不存在!''' % Shopping_Chart_Choose)
                    elif Add_Shoppping_Index == 'q':
                        print('''\n\t\t序号\t\tname\t\tprice\t\tnum\t\t''')
                        ThroughShoppingDic(Shopping_Chart)
                        WriteShoppingProductFile(Shopping_Chart)
                        print('''您的余额为:%s''' % Balance)
                        with open("user.txt", 'r+', encoding='utf-8') as f:
                            User_Info = name + "" + str(Balance)
                            f.writelines(User_Info + "\n")
                    else:
                        print("invalid option")
                    Break_Flag = Break_Flag
            elif Shopping_Chart_Choose==3:
                print('''\n\t\t序号\t\tname\t\tprice\t\tnum\t\t''')
                ThroughShoppingDic(Shopping_Chart)
                Exit_System()
            else:
                continue
        else:
            print('''\n\t\t序号\t\tname\t\tprice\t\tnum\t\t''')
            ThroughShoppingDic(Shopping_Chart)
            WriteShoppingProductFile(Shopping_Chart)
            print('''您的余额为:%s''' %Balance)
            with open("user.txt", 'r+', encoding='utf-8') as f:
                User_Info = name + "" + str(Balance)
                f.writelines(User_Info + "\n")
            Exit_System()

    管理员程序:

    #!/usr/bin/env python 
    # _*_ encoding:utf-8 _*_
    # author:snate
    # 将商品列表从文件中读出,并写入字典
    def ReadProductDic():
        with open('Product_List.txt', 'r', encoding="utf-8") as f:
            for line in f:
                Product_Info = line.strip("\n").split(" ")
                Index = int(Product_Info[0])
                Product_Name = Product_Info[1]
                Product_Price = Product_Info[2]
                Product_List[Product_Name] = int(Product_Price)
                print(Index,Product_Name,Product_List[Product_Name])
    def WriteShoppingProductFile(Product_List):
        with open('Product_List', 'w', encoding="utf-8") as f:
            for index,Product_Name in enumerate(Product_List):
                index = str(index)
                Product_Price= str(Product_List[Product_Name])
                Product_Str=index+" "+ Product_Name + " " + Product_Price
                f.writelines(Product_Str+"\n")
    
    if __name__ == '__main__':
        Product_List = {}
        ReadProductDic()
        Modify_Product_Name = input("请输入要修改价格的商品:")
        Modify_Product_Price = input("请输入要修改的价格:")
        if  Modify_Product_Name in Product_List:
            if Modify_Product_Price.isdigit():
                Modify_Product_Price = int(Modify_Product_Price)
                Product_List[Modify_Product_Name] = Modify_Product_Price
        else:
            Product_List[Modify_Product_Name] = Modify_Product_Price
        WriteShoppingProductFile(Product_List)
    

      流程图:

     字符串

    name = "Nihaonihaoxlwpxxa"
    print(name.capitalize())  # 首字母大写
    print(name.count("nihao"))  # 统计某个字符或者字符串出现的次数
    print('''My name is :{name},my age is {age}'''.format(name="gxw",age=26))  # 标准化输出
    print(name.isalnum())  # 是否为阿拉伯数字
    print(name.isalpha())  # 是否全为纯英文字母
    print(name.isdigit())  # name是否为整数
    print(name.istitle())  # 判断首字母是否大写
    print(name.islower())  # 判断是否全为小写
    print(name.isupper())  # 判断是否全为大写?
    print(name.strip())  # 去掉 name中的空格和回车
    print(name.strip().split())  # 去掉空格后,再空格分隔,返回列表
    print(name.startswith("N"))  # 是否以N开头
    # print("+".join([1,2]))   # t
    print(" ".join(["nihao","wohenhao"])) # 备注:可以将列表转化成字符串,但是列表的元素必须为字符或者是字符串,否则会报错!
    p=str.maketrans("abcd","123$") # 生成字典 a:1 b:2  c:3 d:$
    print(p)
    print(name.swapcase())  # 小写变大写
    print(name.split()) # 以空格为单位,将字符串分隔

     字典

    Python字典是另一种可变容器模型,且可存储任意类型对象,如字符串、数字、元组等其他容器模型

    #!/usr/bin/env python 
    # _*_ encoding:utf-8 _*_
    
    Product_List={"iPad":3500,
                  "Kindle":1699,
                  "MI Pad":1499,
                  "IMAC":20000,
                  "MP3":200
                  }
    # 遍历1
    for  index ,Product in enumerate(Product_List):
        print(index,Product)
    # 遍历2
    for product in Product_List:
        print(product,Product_List[product])
    # 遍历3
    for k,v in Product_list.item():
       print(k,v)
    
    
    info.setdefault("stu1104","alex")
    print(info)
    keys = info.keys()
    print(keys)
    print(info.keys())
    print(info.values())
    更新
    b = {1:2,3:4, "stu1102":"龙泽萝拉"}
    print(info.update(b))
    # 增
    info["stu1104"] = "wo hen bu hao"
    # 改
    info["stu1101"] = "nihao"
    print(info)
    #删
    del info["stu1101"]
    info.pop("stu1101")
    print(info)
    #查
    print("stu1101" in info)
    print("stu1102" in info)
    print(info.get("stu1102"))  
    print(info.get("stu1105"))
    print(info["stu1105"]) # #如果一个key不存在,就报错,get不会,不存在只返回None
    av_catalog = {
        "欧美":{
            "www.youporn.com": ["很多免费的,世界最大的","质量一般"],
            "www.pornhub.com": ["很多免费的,也很大","质量比yourporn高点"],
            "letmedothistoyou.com": ["多是自拍,高质量图片很多","资源不多,更新慢"],
            "x-art.com":["质量很高,真的很高","全部收费,屌比请绕过"]
        },
        "日韩":{
            "tokyo-hot":["质量怎样不清楚,个人已经不喜欢日韩范了","听说是收费的"]
        },
        "大陆":{
            "1024":["全部免费,真好,好人一生平安","服务器在国外,慢"]
        }
    }
    
    av_catalog["大陆"]["1024"][1] = ",可以用爬虫爬下来"
    print(av_catalog["大陆"]["1024"])
    

      

  • 相关阅读:
    [内核编程] 串口过滤
    大数问题(高精度运算)
    [内核编程] 实战调试,第一个内核程序
    [内核编程] Windebug双机调试环境搭建
    树状数组
    mysql常用语句
    解决maven工程无法创建src/main/java包名的方法
    java Date中方法toLocaleString过时的替代方案
    Eclipse 无法编译,提示“错误: 找不到或无法加载主类”
    Eclipse如何设置编译文件.class输出路径
  • 原文地址:https://www.cnblogs.com/itlinux/p/5723060.html
Copyright © 2011-2022 走看看