Python知识点备忘录

发布时间:2019-06-21 17:33:18编辑:auto阅读(1676)

    文件开头:

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #上面一行适用于3以前的版本

    当行注释:# 注释
    多行注释:""" 注释 """  或  '''注释'''

    输入密码:

    import getpass
    pwd = getpass.getpass("请输入密码:")

    模块查找路径:

    import sysprint(sys.path)#['', 'D:\\Program Files\\Python35\\python35.zip', ...
    #空格代表与执行文件同一目录,非当前路径
    #但在Python的命令行模式下,则代表当前路径

    命令行参数:

    import sys
    print(sys.argv)

    Python命令行模式下自动补全功能(linux):

    #!/usr/bin/env python 
    # python startup file 
    import sys
    import readline
    import rlcompleter
    import atexit
    import os
    # tab completion 
    readline.parse_and_bind('tab: complete')
    # history file 
    histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
    try:
        readline.read_history_file(histfile)
    except IOError:
        pass
    atexit.register(readline.write_history_file, histfile)
    del os, histfile, readline, rlcompleter

    定义子程序:

    Python用def,perl用sub,JavaScript用function。别再搞错了,你这个sb

    列表切片:

    >>> num = [0,1,2,3,4,5]
    >>> num[1:4]   #取下表1~3的值,
    [1, 2, 3]
    >>> num[1:-1] #取下标1至-1的值,不包括-1
    [1, 2, 3, 4]
    >>> num[0:3]  
    [0, 1, 2]
    >>> num[:3]  #0可以省略
    [0, 1, 2]
    >>> num[::2]  #第三个参数代表步长
    [0, 2, 4]

    追加与插入:

    >>> num.append(6)
    >>> num
    [0, 1, 2, 3, 4, 5, 6]
    >>> num.insert(0,-1)  #第一个参数表示插入元素的下标
    >>> num
    [-1, 0, 1, 2, 3, 4, 5, 6]

    列表合并:

    >>> alpha = ['a','b','c','d']
    >>> alpha.extend(num)
    >>> alpha
    ['a', 'b', 'c', 'd', -1, 0, 1, 2, 3, 4, 5, 6]

    删除与批量删除:

    >>> alpha.remove('c')
    >>> alpha
    ['a', 'b', 'd', -1, 0, 1, 2, 3, 4, 5, 6]
    >>> alpha.pop()    #remove and return item at index (default last).可带参数,指定要删除元素的下标
    6
    >>> alpha
    ['a', 'b', 'd', -1, 0, 1, 2, 3, 4, 5]
    >>> del alpha[1:4]
    >>> alpha
    ['a', 0, 1, 2, 3, 4, 5]

    浅拷贝:

    >>> list1 = [0,1,[2,3,4],5,6]
    >>> list2 = list1.copy()
    >>> list2
    [0, 1, [2, 3, 4], 5, 6]
    >>> list1[2][2]=3
    >>> list2
    [0, 1, [2, 3, 3], 5, 6]

    深拷贝:

    import copy
    >>> list3 = copy.deepcopy(list1)
    >>> list1[2][2]=4
    >>> list3
    [0, 1, [2, 3, 3], 5, 6]
    >>> list1
    [0, 1, [2, 3, 4], 5, 6]

    获取下标:

    >>> alpha
    [5, 4, 3, 2, 1, 0, 'b', 'a']
    >>> alpha.index('b')
    6
    >>> alpha.index('d')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: 'd' is not in list

    统计数量:

    >>> list3
    [0, 1, [2, 3, 3], 5, 6]
    >>>
    >>>
    >>> list3.count(1)
    1
    >>> list3.count(3)
    0

    排序、翻转、清空:

    >>> alpha.sort()            #排序只能是纯数字或字符串,不同类型无法排序
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unorderable types: str() < int()
    
    >>> a2 = ['2','1']
    >>> a2.sort()
    >>> a2
    ['1', '2']
    >>>
    >>> a3 = ['b','d','a','c']
    >>> a3.sort()
    >>> a3
    ['a', 'b', 'c', 'd']
    >>>
    >>> alpha.reverse()
    >>> alpha
    [5, 4, 3, 2, 1, 0, 'b', 'a']
    
    >>> list1.clear()
    >>> list1
    []

    元组(tuple):

    tuple.count()

    tuple.index()

    字符串:

    大部分操作同数组。

    去除首尾space字符:

    >>> s = "   sdfjlsjdflks   "
    >>> s
    '   sdfjlsjdflks   '
    >>>
    >>> s.strip()
    'sdfjlsjdflks'
    >>> s
    '   sdfjlsjdflks   '   #strip不会改变原字符串,只会返回去除space后的字符串

    左右填充与居中填充:

    >>> s = "hello,world"
    >>> s.ljust(40,"#")
    'hello,world#############################'
    >>> s.rjust(40,"#")
    '#############################hello,world'
    >>> s.center(40,"#")
    '##############hello,world###############'

    翻译:

    >>> s = "Hello World!"
    >>> p = str.maketrans("abcdefg","3!@#$%^")
    >>> s.translate(p)
    'H$llo Worl#!

    字典:

    >>> dic1 = {'no1':12,'no2':13,'no3':11}
    >>> dic1
    {'no1': 12, 'no2': 13, 'no3': 11}
    >>>
    >>> dic1.pop('no1')
    12
    >>> dic1
    {'no2': 13, 'no3': 11}
    >>> del dic1['no2']
    >>> dic1
    {'no3': 11}
    >>> dic1['no4'] = 33
    >>> dic1
    {'no4': 33, 'no3': 11}
    >>> dic1.popitem()  #随机删除
    ('no4', 33)
    >>> dic1
    {'no3': 11}

    获取和查找:

    >>> dic = {"zs":33,"ls":45,"ww":56,"zl":90}
    >>> dic['dd']
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'dd'
    >>> dic.get('dd')    #避免报错
    >>> 'ls' in dic         #判断字典里是否有某个键,用in
    True

    获取keys和values列表:

    >>> dic.values()
    dict_values([45, 33, 56, 90])
    >>> dic.keys()
    dict_keys(['ls', 'zs', 'ww', 'zl'])

    update:

    >>> dic
    {'ls': 45, 'zs': 33, 'ww': 56, 'zl': 90}
    >>> dic2
    {'zs': 33, 'kk': 99, 'ls': 33, 'ww': 44, 'zl': 90}
    >>>
    >>> dic.update(dic2)
    >>> dic
    {'kk': 99, 'zl': 90, 'ls': 33, 'zs': 33, 'ww': 44}

    遍历:

    #方法1
    for key in info:
        print(key,info[key])
        
    #方法2
    for k,v in info.items(): #会先把dict转成list,数据里大时莫用
        print(k,v)

    集合

    s = set([3,5,9,10])      #创建一个数值集合  
    t = set("Hello")         #创建一个唯一字符的集合  
    
    a = t | s          # t 和 s的并集  
    b = t & s          # t 和 s的交集  
    c = t – s          # 求差集(项在t中,但不在s中) 
    d = t ^ s          # 对称差集(项在t或s中,但不会同时出现在二者中) 
       
      
    基本操作:  
    t.add('x')            # 添加一项  
    s.update([10,37,42])  # 在s中添加多项  
       
    使用remove()可以删除一项:  
    t.remove('H')  
      
    len(s)  
    set 的长度  
      
    x in s  
    测试 x 是否是 s 的成员  
      
    x not in s  
    测试 x 是否不是 s 的成员  
      
    s.issubset(t)  
    s <= t  
    测试是否 s 中的每一个元素都在 t 中  
      
    s.issuperset(t)  
    s >= t  
    测试是否 t 中的每一个元素都在 s 中  
      
    s.union(t)  
    s | t  
    返回一个新的 set 包含 s 和 t 中的每一个元素  
      
    s.intersection(t)  
    s & t  
    返回一个新的 set 包含 s 和 t 中的公共元素  
      
    s.difference(t)  
    s - t  
    返回一个新的 set 包含 s 中有但是 t 中没有的元素  
      
    s.symmetric_difference(t)  
    s ^ t  
    返回一个新的 set 包含 s 和 t 中不重复的元素  
      
    s.copy()  
    返回 set “s”的一个浅复制

    文件操作:

    打开与打开模式:

    F=open('path/file','r') 只读

    F=open('path/file','w') 只写,存在则清空,不存在则创建

    F=open('path/file','x')  3.0版本,只写,文件存在则报错,不存在则创建

    F=open('path/file','a')  追加

    其他模式:


    指定编码:

    mfile = open('files/chianMap.txt','r',encoding="utf-8")

    读取:

    mfile.read(n)  #默认读取字符,在‘b’模式下,按字节读取。



关键字