• Oldman python of full stack-Day2


    Directory:

    1.List, tuple action

    2.String operations

    3.Dictionary operations

    4.Set

    5.File operations

    6.Character encoding and transcoding

    ----------------------------------------------------------------------

    1.List and Tuples

    names = ['Alex',"Tenglan",'Eric']
    >>> names[0]
    'Alex'
    >>> names[2]
    'Eric'
    >>> names[-1]
    'Eric'
    >>> names[-2] 
    'Tenglan'

    Lists are modifiable (or 'mutable', as a programmer may say), so their values can be changed. Most of the time we use lists, not tuples, because we want to easily change the values of things if we need to.

    Slice: take multiple elements

    >>> names = ["Alex","Tenglan","Eric","Rain","Tom","Amy"]
    >>> names[1:4]  #取下标1至下标4之间的数字,包括1,不包括4
    ['Tenglan', 'Eric', 'Rain']
    >>> names[1:-1] #取下标1至-1的值,不包括-1
    ['Tenglan', 'Eric', 'Rain', 'Tom']
    >>> names[0:3] 
    ['Alex', 'Tenglan', 'Eric']
    >>> names[:3] #如果是从头开始取,0可以忽略,跟上句效果一样
    ['Alex', 'Tenglan', 'Eric']
    >>> names[3:] #如果想取最后一个,必须不能写-1,只能这么写
    ['Rain', 'Tom', 'Amy'] 
    >>> names[3:-1] #这样-1就不会被包含了
    ['Rain', 'Tom']
    >>> names[0::2] #后面的2是代表,每隔一个元素,就取一个
    ['Alex', 'Eric', 'Tom'] 
    >>> names[::2] #和上句效果一样
    ['Alex', 'Eric', 'Tom']

    Adding items to a list:

    append:

    >>> names
    ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy']
    >>> names.append("new_name")
    >>> names
    ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', 'new_name']

    insert:

    >>> names
    ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']
    >>> names.insert(2,"强行从Eric前面插入")
    >>> names
    ['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', 'Tom', 'Amy', '我是新来的']
    
    >>> names.insert(5,"从eric后面插入试试新姿势")
    >>> names
    ['Alex', 'Tenglan', '强行从Eric前面插入', 'Eric', 'Rain', '从eric后面插入试试新姿势', 'Tom', 'Amy', '我是新来的']

    Modify tuples

    >>> names
    ['Alex', 'Tenglan', 'Winter', 'Eric', 'Rain', 'vince', 'Tom', 'Amy', 'new_name']
    >>> names[2] = "new_Winter"
    >>> names
    ['Alex', 'Tenglan', 'new_Winter', 'Eric', 'Rain', 'vince', 'Tom', 'Amy', 'new_name']

    Deleting an item

    >>> del names[2] 
    >>> names
    ['Alex', 'Tenglan', 'Eric', 'Rain', 'vince', 'Tom', 'Amy', 'new_name']
    >>> del names[4]
    >>> names
    ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy', 'new_name']
    >>> 
    >>> names.remove("Eric")
    >>> names
    ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 'new_name']
    >>> names.pop() #delete the last element(default)
    'new_name'
    >>> names
    ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']

    extend

    >>> names
    ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy']
    >>> b = [1,2,3]
    >>> names.extend(b)
    >>> names
    ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]

    copy

    >>> names
    ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]
    
    >>> name_copy = names.copy()
    >>> name_copy
    ['Alex', 'Tenglan', 'Rain', 'Tom', 'Amy', 1, 2, 3]

    count

    >>> names
    ['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3]
    >>> names.count("Amy")
    2

    sort and reverse

    >>> names
    ['Alex', 'Tenglan', 'Amy', 'Tom', 'Amy', 1, 2, 3]
    >>> names.sort() #sort
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unorderable types: int() < str()   
    >>> names[-3] = '1'
    >>> names[-2] = '2'
    >>> names[-1] = '3'
    >>> names
    ['Alex', 'Amy', 'Amy', 'Tenglan', 'Tom', '1', '2', '3']
    >>> names.sort()
    >>> names
    ['1', '2', '3', 'Alex', 'Amy', 'Amy', 'Tenglan', 'Tom']
    
    >>> names.reverse() #reverse
    >>> names
    ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1']

    To obtain the subscript 

    >>> names
    ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1']
    >>> names.index("Amy")
    2 

     -------------------------------------------------------------------------------------------------

    2.String

    Features:unmodifiable

    name.capitalize()  首字母大写
    name.casefold()   大写全部变小写
    name.center(50,"-")  输出 '---------------------Alex Li----------------------'
    name.count('lex') 统计 lex出现次数
    name.encode()  将字符串编码成bytes格式
    name.endswith("Li")  判断字符串是否以 Li结尾
     "Alex	Li".expandtabs(10) 输出'Alex      Li', 将	转换成多长的空格 
     name.find('A')  查找A,找到返回其索引, 找不到返回-1 
    
    format :
        >>> msg = "my name is {}, and age is {}"
        >>> msg.format("alex",22)
        'my name is alex, and age is 22'
        >>> msg = "my name is {1}, and age is {0}"
        >>> msg.format("alex",22)
        'my name is 22, and age is alex'
        >>> msg = "my name is {name}, and age is {age}"
        >>> msg.format(age=22,name="ale")
        'my name is ale, and age is 22'
    format_map
        >>> msg.format_map({'name':'alex','age':22})
        'my name is alex, and age is 22'
    
    
    msg.index('a')  返回a所在字符串的索引
    '9aA'.isalnum()   True
    
    '9'.isdigit() 是否整数
    name.isnumeric  
    name.isprintable
    name.isspace
    name.istitle
    name.isupper
     "|".join(['alex','jack','rain'])
    'alex|jack|rain'
    
    
    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)
        >>> 
        >>> str = "this is string example....wow!!!"
        >>> str.translate(trantab)
        'th3s 3s str3ng 2x1mpl2....w4w!!!'
    
     msg.partition('is')   输出 ('my name ', 'is', ' {name}, and age is {age}') 
    
     >>> "alex li, chinese name is lijie".replace("li","LI",1)
         'alex LI, chinese name is lijie'
    
     msg.swapcase 大小写互换
    
    
     >>> msg.zfill(40)
    '00000my name is {name}, and age is {age}'
    
    
    
    >>> n4.ljust(40,"-")
    'Hello 2orld-----------------------------'
    >>> n4.rjust(40,"-")
    '-----------------------------Hello 2orld'
    
    
    >>> b="ddefdsdff_哈哈" 
    >>> b.isidentifier() #检测一段字符串可否被当作标志符,即是否符合变量命名规则
    True
    View Code

    3.Dictionary

    info = {
        'stu1101': "TengLan Wu",
        'stu1102': "LongZe Luola",
        'stu1103': "XiaoZe Maliya",
    }
    View Code

    字典的特性:

    • dict是无序的
    • key必须是唯一的,so 天生去重

    add

    >>> info["stu1104"] = "苍井空"
    >>> info
    {'stu1102': 'LongZe Luola', 'stu1104': '苍井空', 'stu1103': 'XiaoZe Maliya', 'stu1101': 'TengLan Wu'}

    modify

    >>> info['stu1101'] = "武藤兰"
    >>> info
    {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': '武藤兰'}
    View Code

    delete

    >>> info
    {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1101': '武藤兰'}
    >>> info.pop("stu1101") #标准删除姿势
    '武藤兰'
    >>> info
    {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
    >>> del info['stu1103'] #换个姿势删除
    >>> info
    {'stu1102': 'LongZe Luola'}
    >>> 
    >>> 
    >>> 
    >>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
    >>> info
    {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'} #随机删除
    >>> info.popitem()
    ('stu1102', 'LongZe Luola')
    >>> info
    {'stu1103': 'XiaoZe Maliya'}
    View Code

    查找

    >>> info = {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya'}
    >>> 
    >>> "stu1102" in info #标准用法
    True
    >>> info.get("stu1102")  #获取
    'LongZe Luola'
    >>> info["stu1102"] #同上,但是看下面
    'LongZe Luola'
    >>> info["stu1105"]  #如果一个key不存在,就报错,get不会,不存在只返回None
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'stu1105'
    View Code

    多级字典嵌套及操作

    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"])
    #ouput 
    ['全部免费,真好,好人一生平安', '服务器在国外,慢,可以用爬虫爬下来']

    其它

    #values
    >>> info.values()
    dict_values(['LongZe Luola', 'XiaoZe Maliya'])
    
    #keys
    >>> info.keys()
    dict_keys(['stu1102', 'stu1103'])
    
    
    #setdefault
    >>> info.setdefault("stu1106","Alex")
    'Alex'
    >>> info
    {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}
    >>> info.setdefault("stu1102","龙泽萝拉")
    'LongZe Luola'
    >>> info
    {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}
    
    
    #update 
    >>> info
    {'stu1102': 'LongZe Luola', 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}
    >>> b = {1:2,3:4, "stu1102":"龙泽萝拉"}
    >>> info.update(b)
    >>> info
    {'stu1102': '龙泽萝拉', 1: 2, 3: 4, 'stu1103': 'XiaoZe Maliya', 'stu1106': 'Alex'}
    
    #items
    info.items()
    dict_items([('stu1102', '龙泽萝拉'), (1, 2), (3, 4), ('stu1103', 'XiaoZe Maliya'), ('stu1106', 'Alex')])
    
    
    #通过一个列表生成默认dict,有个没办法解释的坑,少用吧这个
    >>> dict.fromkeys([1,2,3],'testd')
    {1: 'testd', 2: 'testd', 3: 'testd'}

    循环dict 

    #方法1
    for key in info:
        print(key,info[key])
    
    #方法2
    for k,v in info.items(): #会先把dict转成list,数据里大时莫用
        print(k,v)
    View Code
  • 相关阅读:
    Assembly Manifest 通俗简易手册
    CruiseControl服务器安装配置
    关于URL编码
    从A到Z来说说Web开发
    通过注册表查看 .NET Framework的版本信息
    云数据存在哪里?
    C#中你可能不知道的8件事(zz)
    用PBKDF2 或BCrypt 来存储密码
    C++编译器什么时候为我们自动生成拷贝构造函数?
    C#中你可能不知道的8件事(zz)
  • 原文地址:https://www.cnblogs.com/zijue/p/9791062.html
Copyright © 2020-2023  润新知