美文网首页Python相关
Python随手笔记

Python随手笔记

作者: 低音旋律 | 来源:发表于2020-06-02 17:20 被阅读0次

    pycharm激活码

    http://lookdiv.com/

    解决logging 在docker中报ascii字符编码错误

    cd /usr/lib64/python3.6/encodings/ #python3.x应该都一样
    mv ascii.py ascii.py.bak #这也算给自己留条后路,等将来真找到问题了,还能再恢复回来。
    cp utf_8.py ascii.py

    Except显示错误信息的行号和文件Except显示错误信息的行号和文件

    try:
        print(a)
    except NameError as e:
        print('发生错误的文件:', e.__traceback__.tb_frame.f_globals['__file__'])
        print('错误所在的行号:', e.__traceback__.tb_lineno)
        print('错误信息', e)
    
    print('测试完毕')
    

    if判断简写
    老方法:

    if role:
        role = 'Admin'
    else:
        role = 'User'
    

    简写方法:
    role = 'Admin' if role else 'User'

    request.GET.get('cmd') if request.GET.get('cmd') else 'open'
    

    解读:首先执行if语句中的逻辑,如果成立则执行if左边的代码,如果不成立则执行右边的方法。


    数字向上取整 ceil,与int相反

    import math
     
    print(math.ceil(3))
    print(math.ceil(3.6))
    print(math.ceil(3.1))
    

    字符串

    python字符串可以支持乘法,还支持切片,可以从后往前分割,用[-10:]表示倒数第10个字到尾部。[:10]表示取字符串第十位前面所有的字,string[::-1]可以反转字符串

    格式化字符串
    功能函数:format
    实例:
    print("ccccccc{}ddddddd{}".format('666','777'))

    判断收尾字符串是否成立
    功能函数:startswith() , endswith()
    实例:

    text='welcome to qttc blog'
    print (text.startswith('w'))      # True
    print (text.startswith('wel'))    # True
    print (text.startswith('c'))     # False
    print (text.startswith(''))      # True
    

    有序字典

    python 有序字典OrderedDict
    在python中字典是无序的。有些情况下,需要有序的字典,怎么办呢?用OrderedDict

    >>> from collections import OrderedDict
    >>> a=OrderedDict({})
    >>> a
    OrderedDict()
    >>> a['a'] =1
    >>> a['b'] =2
    >>> a['c']=3
    >>> a
    

    运算
    **代表平方的意思,如2**3 ,结果是8 , 取平方根是 4**0.5,结果是2


    字典、列表、元组去重
    功能函数: set

    set可以去除列表,元组中所有重复的项,还可以将字典的所有键全部取出来


    逻辑判断

    bool(0),bool([]),bool(''),bool(False),bool(None) 都返回false
    

    while循环

    支持else用法,也就是说当循环条件不满足的时候所做的事情
    

    enumerate枚举

    可以直接枚举一个列表,需要用计次循环的方式,他还支持第二个参数,用来指定索引的起始位置(主要目的是可以缩短编写取列表值的过程,如len(list1)后再取每一个列表值)
    默认返回两个参数,第一个是循环次数,第二个是遍历的值如(1,"这"),(2,"是")

    list1 = ["这", "是", "一个", "测试"]
    for index, item in enumerate(list1,1):
        print (index, item)
    
    #如果要统计文件的行数,可以这样写:
    count = 0
    for index, line in enumerate(open(filepath,'r')):
    count += 1
    

    lambda快速函数

    f=lambda x,y:x+y
    print(f(1,2))
    

    map( 函数(有两个参数), 一个或多个序列)

    map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
    [3, 7, 11, 15, 19]
    

    reduce()函数

    reduce(lambda x, y: x+y, [1,2,3,4,5])
    

    函数将1+2得到的结果,再与3进行加法计算,之后再用得到的结果与4进行加法计算,直到列表结束。注意,函数只支持两个参数,并且python3以后需要导入模块from functools import reduce才可以使用。


    string
    可以去除字符串首尾的特殊字符
    实例:

    a="123123!@#$%"    
    print(a.strip(string.punctuation))
    

    sorted

    counts_dict = {'1': '2', '2': '1'}
    for word in sorted(counts_dict,key = lambda x: counts_dict[x],reverse=False):
    print(word)
    

    random

    random.choice(list) 表示可以随机选择列表中的某一个项,同时requests支持代理IP,只需需要在参数中添加proxies=xxx即可。
    

    pow(x,y,z)

    pow(3,2,4) 表示,3的2次方,再取余,#3 ** 2 % 4 -->1
    

    round(xx,123)

    可以进行数字的四舍五入,也可以设置负数
    

    abs(x)

    取X的绝对值。如:abs(-1)  -->1
    

    ord("h")
    参数: 字符。
    返回值:是对应的十进制整数
    >>> 104

    chr(104)
    参数:可以是 10 进制也可以是 16 进制的形式的数字,数字范围为 0 到 1,114,111 (16 进制为0x10FFFF)。
    返回值 : 是当前整数对应的 ASCII 字符。
    >>>'h'

    \ 折行符(用来连接本行和下一行用的,必须放在一行的末尾)print()写文件,在打开的同时可以进行写文件的操作

    with open('abc.txt','w') as f:
        print("file\n","abc","fff",sep='#########\n',end='',file=f)
    

    print的end,sep说明:end是打印完成一行以后最后的符号,默认是换行符。sep是当你打印两个数据的时候,中间用什么分割开来。bin(123)转换为二进制ord(str) 返回一个字符串的ASCII的值chr(i) 返回i这个值所对应的字符max获取continue
    在while 语句中执行continue语句,将会直接跳转到while语句真值表达式处重新判断循环条件,
    在for语句中执行continue语句,将会从可迭代对象中移向下一个元素再次进行循环


    reload [模块名]

    重新导入一次模块,模块导入两次或多次不会重复运行,想重复运行就需要使用reload


    字符串方法1(join):
    '-'.join('12345') ( #a=["1","2","3","4"]       #print("-".join(a)))
    

    字符串方法2(format):
    s = "This is {1},he is {0}".format('jjj','hhh')
    >>>'This is hhh,he is jjj'
    

    可迭代对象进度条方法:

    pip install tqdm

    from time import sleep
    from tqdm import tqdm
    
    # 这里同样的,tqdm就是这个进度条最常用的一个方法
    # 里面存一个可迭代对象
    
    for i in tqdm(range(1, 500)):
        # 模拟你的任务
        print(i)
        sleep(0.001)
    
    

    获取内存地址(id)

    a = [1,2,3] print(id(a))


    timeit 程序时间测试模块

    timeit.timeit(stmt="[i for i in range(1000)]", number=100000)

    • number:表示执行该函数的次数
    • stmt: 这个参数就是statement,可以把要进行计算时间的代码放在里面。他可以直接接受字符串的表达式,也可以接受单个变量,也可以接受函数。
    • setup: 这个参数可以将stmt的环境传进去。比如各种import和参数什么的。
    • timer: 这个参数一般使用不到,具体使用可以参看文档。

    将可迭代对象转换为字典的方法
    >>> a = zip((1,2),(2,3))
    >>> dict(a)
    {1: 2, 2: 3}
    
    同时迭代两个列表
    nfc = ["aaa","bbb"]
    afc = ["ccc","ddd"]
    for x,y in zip(nfc,afc):
        print(x,y)
    #也可以同时迭代更多
    nfc = ["aaa", "bbb"]
    afc = ["ccc", "ddd"]
    bb = ["aa", "ff"]
    for x, y, z in zip(nfc, afc, bb):
        print(x, y, z)
    

    实例1:

    a = "123"
    b = 2
    c = a*b
    print(c)
    

    实例2:

    url = 'http://ww1.site.cn/14d2e8ejw1exjogbxdxhj20ci0kuwex.jpg'
    file_name = url[-10:]
    print(file_name)
    

    实例3:

    url =phone_number = '1386-666-0006'
    hiding_number = phone_number.replace(phone_number[:9],'*' * 9)
    print(hiding_number)
    

    实例4:

    print('{} a word she can get what she {} for.'.format('With','came'))
    city = input("write down the name of city:")
    url = "http://apistore.baidu.com/microservice/weather?citypinyin={}".format(city)
    

    实例5:

    a={'1':'1','2':'1','3':'1','5':'1','2':'1'}
    b=set(a)
    print(b)
    

    字典同时取出键和值:

    dict = {'Name': 'Runoob', 'Age': 7}
    for i,j in dict.items(): #items以列表返回可遍历的(键, 值) 元组数组
        print(i, ":\t", j)
    

    autopep8编码规范:
    D:\python\Scripts\autopep8.exe --in-place --aggressive --aggressive D:\pytestt\flask\Q_text.py

    异步说明:
    程序在顺序执行的时候,将信号告知给系统内核,内核会在约定时间后再告知应用层处理某事

    相关文章

      网友评论

        本文标题:Python随手笔记

        本文链接:https://www.haomeiwen.com/subject/pmfpzhtx.html