美文网首页
不怎么用到的Python技巧(1)

不怎么用到的Python技巧(1)

作者: 赤色要塞满了 | 来源:发表于2019-03-17 23:23 被阅读0次

    获取Python的保留字

    >>> import keyword
    >>> print(keyword.kwlist)
    ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
    

    判断是不是数字

    >>> '十四'.isnumeric()
    True
    >>> '十四'.isdigit()
    False
    >>> '十四'.isdecimal()
    False
    

    字符串对齐

    >>> 'a'.rjust(5,'#')
    '####a'
    >>> 'a'.center(8,'#')
    '###a####'
    >>> 
    

    具名元组

    >>> import collections
    >>> Dog = collections.namedtuple('dogs', ['name', 'age', 'weight'])
    >>> dog1 = Dog('Toto', 5, 20)
    >>> dog1
    dogs(name='Toto', age=5, weight=20)
    >>> dog1._asdict()
    OrderedDict([('name', 'Toto'), ('age', 5), ('weight', 20)])
    

    print()的参数

    >>> print(1, 2, 3, sep = '-')
    1-2-3
    >>> print(1, 2, 3, end = '/')
    1 2 3/
    

    局部变量

    >>> a = 10    
    >>> def test():
          "赋值则变成局部变量(这句通过__doc__可以查看)"
          a = a + 1
          print(a)
          
    >>> test()    
    Traceback (most recent call last):
      File "<pyshell#244>", line 1, in <module>
        test()
      File "<pyshell#243>", line 2, in test
        a = a + 1
    UnboundLocalError: local variable 'a' referenced before assignment
    

    队列

    不用直接用list做队列,其出列太耗资源。

    >>> from collections import deque  
    >>> q = deque([1, 2, 3])  
    >>> q.append(4)  
    >>> q 
    deque([1, 2, 3, 4])
    >>> q.popleft()
    1
    >>> q
    deque([2, 3, 4])
    

    迭代器

    实现__iter__即可

    class MyCounter():
        def __iter__(self):
            self.a = 1
            return self
    
        def __next__(self):
            x = self.a
            self.a += 1
            return x
    
    mycounter = MyCounter()
    myiter = iter(mycounter)
    print(next(myiter))
    

    漂亮打印pprint

    没啥用

    >>> from pprint import pprint
    >>> pprint({"adf":123, "jj":8724}, indent=4, width=4)
    {   'adf': 123,
        'jj': 8724}
    

    pickle与json

    >>> import pickle, json
    >>> data1 = {'abc': 1+2j}
    >>> p = open('data.pkl', 'wb') # 必须是二进制bytes
    >>> pickle.dump(data1, p)
    >>> data2 = {'abc':123} #不能有复数
    >>> f = open('data.json', 'w') # 必须是字符串str
    >>> json.dump(data2, f)
    

    Python也有reduce

    >>> from functools import reduce
    >>> reduce(lambda x,y: x+y, [1,2,3])
    

    偏函数

    固定了某函数的默认参数的函数

    >>> from functools import partial
    >>> max10 = partial(max, 10)
    >>> max10(1,2)
    10
    

    进程线程协程

    这篇不错搞定python多线程和多进程


    base64编码

    >>> b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    >>> ord('1')
    49
    >>> bin(49)
    '0b110001'
    >>> s = str(bin(49))
    >>> s
    '0b110001'
    >>> s = s[2:].zfill(8).ljust(24, '0')
    >>> s
    '001100010000000000000000'
    >>> s = [s[:6], s[7:12], s[13:18], s[19:]]      
    >>> s       
    ['001100', '10000', '00000', '00000']
    >>> b64[int(s[0], 2)]
    'M'
    

    json序列化保留中文

    >>> json.dumps({'asdf':'北京'}, ensure_ascii=False)
    '{"asdf": "北京"}'
    

    相关文章

      网友评论

          本文标题:不怎么用到的Python技巧(1)

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