zoukankan      html  css  js  c++  java
  • python基础2

    1.列表元组

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

    定义列表:

    1 # yu
    2 
    3 names=["啦啦","嘿嘿",'鱼鱼']

    我们通过列表下标进行数据的提取:

    1 # yu
    2 names=["啦啦","嘿嘿",'鱼鱼']
    3 print(names)
    4 print(names[0])#第一个数据从0开始
    5 print(names[-1])#倒过来取值

    切片:

    1 # yu
    2 names=["lala","heihei",'yuyu','hehe','haha']
    3 print(names[1:3])#取下标1 ,不包含下标3 ['heihei', 'yuyu']
    4 print(names[1:-1])#取下标1至-1的值,不包括-1
    5 print(names[:3])#如果是从头开始取,0可以忽略
    6 print(names[3:])#取到最后一个值
    7 print(names[3:-1])#取不到最后一个值
    8 print(names[0::2])#后面的2是代表,每隔一个元素,就取一个
    View Code

    追加:

    1 # yu
    2 names=["lala","heihei",'yuyu','hehe','haha']
    3 names.append("嘻嘻")
    4 print(names)
    5 #结果['lala', 'heihei', 'yuyu', 'hehe', 'haha', '嘻嘻']
    View Code

    插入:

    1 # yu
    2 names=["lala","heihei",'yuyu','hehe','haha']
    3 names.insert(2,'从2插入')
    4 print(names)
    5 #结果['lala', 'heihei', '从2插入', 'yuyu', 'hehe', 'haha']
    View Code

    修改:

    1 # yu
    2 names=["lala","heihei",'yuyu','hehe','haha']
    3 names[1]='修改下标为1'
    4 print(names)
    5 #结果['lala', '修改下标为1', '从2插入', 'yuyu', 'hehe', 'haha']
    View Code

    删除:

    1 names=["lala","heihei",'yuyu','hehe','haha']
    2 #names.clear()#清空列表
    3 print(names)#返回[]
    4 #del names[1]#删除指定下标的值
    5 print(names)#['lala', 'yuyu', 'hehe', 'haha'
    6 #names.remove("yuyu")#删除指定的值
    7 print(names)
    8 names.pop()#默认删最后一个,也可以加入你祥删除的下标
    9 print(names)
    View Code

    扩展:

    1 # yu
    2 names=["lala","heihei",'yuyu','hehe','haha']
    3 b=[1,2,3]
    4 names.extend(b)
    5 print(names)#['lala', 'heihei', 'yuyu', 'hehe', 'haha', 1, 2, 3]
    View Code

    拷贝(浅拷贝与深拷贝的区别):

    1 names=["Young","Jon",["Tom","Jerry"],'Jems','Sunny']
    2 names2 = names.copy()
    3 names[1]="浅copy"
    4 names[2][0]="深copy"
    5 print('name1:',names)
    6 print('name2:',names2)
    7 #结果
    8 #name1: ['Young', '浅copy', ['深copy', 'Jerry'], 'Jems', 'Sunny']
    9 #name2: ['Young', 'Jon', ['深copy', 'Jerry'], 'Jems', 'Sunny']
    View Code

    统计:

    1 # yu
    2 names=["lala","heihei",'yuyu','hehe','haha','haha']
    3 print(names.count('haha'))#结果2
    View Code

    排序:

    1 # yu
    2 names=["1lala","3heihei",'5yuyu','4hehe','2haha','1haha']
    3 names.sort()
    4 print(names)
    View Code

    反转:

    1 names=["1lala","2heihei",'3yuyu','4hehe','5haha','6haha']
    2 names.reverse()
    3 print(names)
    4 #结果['6haha', '5haha', '4hehe', '3yuyu', '2heihei', '1lala']
    View Code

    获取下标:

    1 # yu
    2 names=["0lala","1heihei",'2yuyu','3hehe','4haha','5haha']
    3 print(names.index("2yuyu"))#2
    View Code

    元组

    元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表

    定义:

    names=("lala","heihei",'yuyu','hehe','haha','haha')

    它只有2个方法,一个是count,一个是index.

    2.字符串操作

    特性;不可修改.

    # yu
    name='young'
     #首字母大写
    print(name.capitalize() )
    # name.casefold()   大写全部变小写
    print(name.center(50,"-") ) #输出----------------------young-----------------------
    # name.count('lex') 统计 lex出现次数
    # name.encode()  将字符串编码成bytes格式
    # name.endswith("g")  判断字符串是否以g结尾
    #  "Young	Y".expandtabs(10) 输出'Young      Y', 将	转换成多长的空格
    print(name.find('o'))  #查找A,找到返回其索引, 找不到返回-1
     1 #format
     2 cata = "my name is {}, and age is {}"
     3 print(cata.format("young",23))#结果my name is young, and age is 23
     4 cata = "my name is {}, and age is {}"
     5 print(cata.format("23",'young'))#my name is 23, and age is young
     6 cata = "my name is {name}, and age is {age}"
     7 print(cata.format(age=23,name='young'))
     8 
     9 #format_map
    10 cata = "my name is {name}, and age is {age}"
    11 print(cata.format_map({'name':'young','age':23}))
    View Code
    cata = "my name is {name}, and age is {age}"
    print(cata.index('a'))
    print('9aA'.isalnum() )
    print('9'.isdigit() )#是否整数)
    name='Hello'
    print(name.isnumeric  )
    # name.isprintable
    # name.isspace
    # name.istitle
    # name.isupper
    print("|".join(['lala','hihi','wow']))
    View Code
    #maketrans
    intab = "aeiou"  #This is the string having actual characters.
    outtab = "12345" #This is the string having corresponding mapping character
    trantab = str.maketrans(intab, outtab)
    print(trantab)
    str = "this is string example....wow!!!"
    print(str.translate(trantab))
    #     'th3s 3s str3ng 2x1mpl2....w4w!!!'
    View Code
    1 print(cata.partition('is'))#('my name ', 'is', ' {name}, and age is {age}')
    2 print(cata.swapcase())#大小写互换
    3 print(cata.zfill(40))
    4 n='hello world'
    5 print(n.ljust(40, "-"))
    6 print(n.rjust(40, "-"))
    7 b="ddefdsdff_哈哈" 
    8 b.isidentifier() #检测一段字符串可否被当作标志符,即是否符合变量命名规则
    View Code

     3.字典操作

    字典一种key - value 的数据类型.

    定义:

    info = {
        "1":"嘻嘻",
        "2":"哈哈",
        "3":"呵呵",
        "4":"嘿嘿"
    }

    字典的特性:

    • dict是无序的
    • key必须是唯一的

    增删改查:

    #
    info["5"]="哇哇"
     #
     info["1"]="么么"
     print(info)
    #
    info.pop("1")
    #del info["1"]
    #info.popitem()#随机删除
    #
    print("3" in info)
    print(info["3"])
    print(info.get("2"))
    print(info)
    View Code

    其他方法:

    print(info.keys())
    print(info.values())
    
    info2 = {
        "5":'啦啦',
        '6':'哼哼'
    }
    info.update(info2)
    print(info)
    print(info.setdefault("1","大少"))
    
    print(info.items())
    View Code

    循环dict:

    #两种方法:
    for key in info:
        print(key,info[key])
    
    for k,v in info.items():
        print(k,v)
    View Code

    三级菜单:

    1. 打印省、市、县三级菜单
    2. 可返回上一级
    3. 可随时退出程序
    data = {
        '黑龙江':{
            "哈尔滨":{
                "南岗":["凯德","许乐会所"],
                "松北":["君慕稀","大保健"]
            },
            "牡丹江":{
                "镜泊湖":["大山","河流"],
                "好地方":{"优美","地灵"},
                "小城":{"故事","美好"},
            },
            "海淀":{},
        },
        '山东':{
            "德州":{},
            "青岛":{},
            "济南":{}
        },
        '广东':{
            "东莞":{},
            "常熟":{},
            "佛山":{},
        },
    }
    
    exit_flag = False
    while not exit_flag:
        for i in data:
            print(i)
            choice = input(">>选择进入1")
            if choice  in data:
                while not exit_flag:
                    for i2 in data[choice]:
                        print("	",i2);
                    choice2 = input(">>选择进入2")
                    if choice2 in data[choice]:
                        while not exit_flag:
                            for i3 in data[choice][choice2]:
                                print("		", i3);
                            choice3 = input(">>选择进入3")
                            if choice3 in data[choice][choice2]:
                                for i4 in data[choice][choice2][choice3]:
                                    print("		", i4);
                                choice4 =input("最后一次,按b返回")
                                if choice4 =="b":
                                    pass
                                elif choice4 =="q":
                                     exit_flag=True;
                            if choice3 == "b":
                                 break
                            elif choice3 == "q":
                                exit_flag = True;
                    if choice2 == "b":
                        break
                    elif choice2 == "q":
                        exit_flag = True;
    View Code

    4.集合操作

    集合是一个无序的,不重复的数据组合,它的主要作用如下:

    • 去重,把一个列表变成集合,就自动去重了
    • 关系测试,测试两组数据之前的交集、差集、并集等关系

    常用操作:

    #定义一个集合
    list1=[1,23,4,5,6,0]
    list1 =set(list1)
    list2=set([1,2,7,8,9,0])
    '''
    print (list1)
    print(list2)
    
    #交集
    print(list1.intersection(list2))
    print(list1 & list2)
    #并集
    print(list1.union(list2))
    print(list1 | list2)
    #差集
    print(list1.difference(list2))
    print(list1 - list2)
    
    #子集
    list3 = set([1,2,3,4])
    list4 = set([1,2])
    list5 = set([0,9])
    print(list4.issubset(list3))
    print(list3.issuperset(list4))
    #对称差集
    print(list1.symmetric_difference(list2))
    
    
    print("-----------------------")
    print(list3.isdisjoint(list5))#看有没有交集,并返回true or false;
    
    '''
    #添加,没有插入
    list1.add(12)
    print(list1)
    #
    print(list1.pop())
    print(list1.pop())
    print(list1)
    list1.discard(23)
    print(list1)
    View Code

    5.文件操作

    对文件操作流程

    1. 打开文件,得到文件句柄并赋值给一个变量
    2. 通过句柄对文件进行操作
    3. 关闭文件 

    文件text:

    晚风轻拂着澎湖湾
    白浪逐沙滩
    没有椰林醉斜阳
    只是一片海蓝蓝
    坐在门前的矮墙上一遍遍幻想
    也是黄昏的沙滩上有着脚印两对半
    那是外婆拄着杖将我手轻轻挽
    踩着薄暮走向余晖暖暖的澎湖湾
    一个脚印是笑语一串消磨许多时光
    直到夜色吞没我俩在回家的路上
    澎湖湾澎湖湾外婆的澎湖湾
    有我许多的童年幻想
    阳光沙滩海浪仙人掌
    还有一位老船长
    View Code

    基本操作:

    1 f = open("外婆的澎湖湾",encoding='utf-8')#文件句柄,
    2 # f.write("hello world
    ".encode())
    3 f1 = f.readline()
    4 print('first line:',f1)
    5 print('我是分隔线'.center(50,'-'))
    6 data = f.read()# 读取剩下的所有内容,文件大时不要用
    7 print(data) #打印文件
    8 f.close()
    View Code

    打开文件的模式有:

    • r,只读模式(默认)。
    • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
    • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

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

    • r+,可读写文件。【可读;可写;可追加】
    • w+,写读
    • a+,同a

    "U"表示在读取时,可以将 自动转换成 (与 r 或 r+ 模式同使用)

    • rU
    • r+U

    "b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

    • rb
    • wb
    • ab

    with语句

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

    1 with open('外婆的澎湖湾','r') as f:
    2      
    3     ...

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

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

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

    6.字符的编码与转码

    参考文章:

    http://www.cnblogs.com/yuanchenqi/articles/5956943.html

    需知:

    1.在python2默认编码是ASCII, python3里默认是unicode

    2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间

    3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string

    python3中:

     1 import sys
     2 print(sys.getdefaultencoding())
     3 s = "你好"
     4 
     5 s_gbk = s.encode("gbk")
     6 
     7 print(s_gbk)#gbk
     8 
     9 print(s.encode())#utf8
    10 
    11 gbk_to_utf8 = s_gbk.decode("gbk").encode("utf-8")
    12 print(gbk_to_utf8)
    View Code
  • 相关阅读:
    linux截图工具
    Git理论知识补充
    Git基本操作(add,commit的理解)
    VS2017 error CS0234: 命名空间“Microsoft”中不存在类型或命名空间名“Office”问题的一种解决方案
    MFC CFileDialog DoModal()无法弹出窗口,直接返回IDCANCEL
    VS2015 、VS2017 MFC输出日志到控制台窗口
    win10 VMware 关闭虚拟机失败导致再打开时显示连接不上虚拟机的一种解决方法
    c语言之位段
    Adobe Acrobat DC 制作多级书签
    MFC基于对画框工程笔记->更改窗口图标以及生成的.exe图标
  • 原文地址:https://www.cnblogs.com/Young111/p/9279591.html
Copyright © 2011-2022 走看看