乱七八糟抱佛脚python知识点自用

参考文献:
https://zhuanlan.zhihu.com/p/54430650
https://blog.csdn.net/Jurbo/article/details/52334345
https://www.liaoxuefeng.com/wiki/

标准库

内建函数

  • any():只要迭代器中有一个元素为真就为真

  • all():迭代器中所有的判断项返回都是真,结果才为真

  • del
    当使用del删除变量指向的对象时,如果对象的引用计数不为1,比如3,那么此时只会让这个引用计数减1,即变为2,当再次调用del时,变为1,如果再调用1次del,此时会真的把对象进行删除

  • sorted
    sorted(seq, key=lambda item: item.property, ascending=True)
    和sort的区别是有返回值,不改变原先列表

  • input(py3)
    读取的是str类型
    一次读取多个空格分隔输入值可以这样:
    a,b,c = input('enter a b c: ').split()

  • map
    map(func, seq)

  • filter
    newseq = filter(boolfunc, seq)

  • zip(a,b,c,..)
    zip()参数可以接受任何类型的序列,同时也可以有两个以上的参数;当传入参数的长度不同时,zip能自动以最短序列长度为准进行截取,获得元组。

  • round(float, 保留位数)

内建数据类型

整型--int
布尔型--bool
字符串--str
列表--list
元组--tuple
字典--dict

list

  • List_name.sort()
    This will sort the given list in place, in ascending order by default. reeverse=False是从小到大排
    mylist = [3,6,3,2,4,8,23]
    sorted(mylist, key=lambda x: x%2==0)

    dict

  • del删除键: del(d1[key1])
  • pop删除键: d1.pop(key1)
  • 合并两个字典: d1.update(d2)
  • 遍历键值对: for key, val in d.items()

os

  • os.getpid()
    Return the current process id.
  • os.chdir(path)
    Change the current working directory to path.
  • os.listdir(path='.')
    Return a list containing the names of the entries in the directory given by path without '.' and '..'
  • os.path.join(path, *paths)
    Join one or more path components intelligently.

time

re

正则表达式

sys

通常用于命令行参数

multiprocessing

Python虽然不能利用多线程实现多核任务,但可以通过多进程实现多核任务。多个Python进程有各自独立的GIL锁,互不影响。
廖雪峰博客

# 子进程要执行的代码
def run_proc(name):
    print('Run child process %s (%s)...' % (name, os.getpid()))

if __name__=='__main__':
    print('Parent process %s.' % os.getpid())
    p = Process(target=run_proc, args=('test',))
    print('Child process will start.')
    p.start()
    p.join()
    print('Child process end.')

如果要启动大量的子进程,可以用进程池的方式批量创建子进程:

def long_time_task(name):
    print('Run task %s (%s)...' % (name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print('Task %s runs %0.2f seconds.' % (name, (end - start)))

if __name__=='__main__':
    print('Parent process %s.' % os.getpid())
    p = Pool(4)    # 进程池大小
    for i in range(5):
        p.apply_async(long_time_task, args=(i,))    # 添加并开始运行
    print('Waiting for all subprocesses done...')
    p.close()    # 对Pool对象调用join()方***等待所有子进程执行完毕,调用close()之后就不能继续添加新的Process了。
    p.join()     # 调用join()之前必须先调用close()
    print('All subprocesses done.')

很多时候,子进程并不是自身,而是一个外部进程。我们创建了子进程后,还需要控制子进程的输入和输出。
subprocess模块可以让我们非常方便地启动一个子进程,然后控制其输入和输出。如果子进程还需要输入,则可以通过communicate()方法输入。

r = subprocess.call(['nslookup', 'www.python.org'])    # 和直接命令行是一样的
print('Exit code:', r)

Process之间肯定是需要通信的,操作系统提供了很多机制来实现进程间的通信。Python的multiprocessing模块包装了底层的机制,提供了Queue、Pipes等多种方式来交换数据。

from multiprocessing import Process, Queue
import os, time, random

# 写数据进程执行的代码:
def write(q):
    print('Process to write: %s' % os.getpid())
    for value in ['A', 'B', 'C']:
        print('Put %s to queue...' % value)
        q.put(value)
        time.sleep(random.random())

# 读数据进程执行的代码:
def read(q):
    print('Process to read: %s' % os.getpid())
    while True:
        value = q.get(True)
        print('Get %s from queue.' % value)

if __name__=='__main__':
    # 父进程创建Queue,并传给各个子进程:
    q = Queue()
    pw = Process(target=write, args=(q,))
    pr = Process(target=read, args=(q,))
    # 启动子进程pw,写入:
    pw.start()
    # 启动子进程pr,读取:
    pr.start()
    # 等待pw结束:
    pw.join()
    # pr进程里是死循环,无法等待其结束,只能强行终止:
    pr.terminate()

threading

  • Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
    • target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.
    • name is the thread name. By default, a unique name is constructed of the form “Thread-N”
    • args is the argument tuple for the target invocation. Defaults to ().
    • kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.
  • threading.Lock
    • Note that Lock is actually a factory function which returns an instance of the most efficient version of the concrete Lock class that is supported by the platform
    • acquire(blocking=True, timeout=-1)
    • release()
      • This can be called from any thread, not only the thread which has acquired the lock.

廖雪峰博客
启动一个线程就是把一个函数传入并创建Thread实例,然后调用start()开始执行

t = threading.Thread(target=loop, name='LoopThread')
t.start()
t.join()
balance = 0
lock = threading.Lock()

def run_thread(n):
    for i in range(100000):
        # 先要获取锁:
        lock.acquire()
        try:
            # 放心地改吧:
            change_it(n)
        finally:
            # 改完了一定要释放锁:
            lock.release()

GIL 是python的全局解释器锁,同一进程中假如有多个线程运行,一个线程在运行python程序的时候会霸占python解释器(加了一把锁即GIL),使该进程内的其他线程无法运行,等该线程运行完后其他线程才能运行。
多进程中因为每个进程都能被系统分配资源,相当于每个进程有了一个python解释器,所以多进程可以实现多个进程的同时运行,缺点是进程系统资源开销大

argparse

parser = argparse.ArgumentParser(description='Process some integers.')
# Filling an ArgumentParser with information about program arguments
# This information is stored and used when parse_args() is called.
>>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
...                     help='an integer for the accumulator')
>>> parser.add_argument('--sum', dest='accumulate', action='store_const',
...                     const=sum, default=max,
...                     help='sum the integers (default: find the max)')
# Later, calling parse_args() will return an object with two attributes, integers and accumulate. 
# The integers attribute will be a list of one or more ints
# the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.

# in a script, parse_args() will typically be called with no arguments, and the ArgumentParser will automatically determine the command-line arguments from sys.argv.

pickle

random

  • random.randint(a, b) 区间整数
    Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).
  • random.choice(seq)
    Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.
  • random.shuffle(x[, random])
    Shuffle the sequence x in place. The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random().
  • random.sample(population, k)
    Return a k length list of unique elements chosen from the population sequence or set.
  • random.random() 零一小数
    Return the next random floating point number in the range [0.0, 1.0).

    enum

    >>> from enum import Enum
    >>> class Color(Enum):
    ...     red = 1
    ...     green = 2
    ...     blue = 3
    >>> type(Color.red)
    <enum 'Color'>
    >>> isinstance(Color.green, Color)
    True

    copy

    copy.deepcopy() copys recursively.

collection

Counter

s = "kjalfj;ldsjafl;hdsllfdhg;lahfbl;hl;ahlf;h"
print(Counter(s))
Out: Counter({'1':9, ';':6, key:cnt(decending)...})

## string
- string.strip()
- string.join(seq)
- string.format(format_string, *args, **kwargs)
    It takes a format string and an arbitrary set of positional and keyword arguments. 
    In most of the cases the syntax is similar to the old %-formatting, with the addition of the {} and with : used instead of %. For example, **'%03.2f'** can be translated to **'{:03.2f}'**.

examples:

>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} '
...  'and the imaginary part {0.imag}.').format(c)

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'

>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
  • string.encode()

语法

异常处理

try:的语句出现异常才会执行except后的语句,如果正常,则执行完try后执行else,如print("all is well!")。finally语句不管有无异常都会执行

什么样的语言能够用装饰器?

函数可以作为参数传递的语言,可以使用装饰器 FIXME 所以?

生成器是特殊的迭代器,

1、列表表达式的【】改为()即可变成生成器
2、函数在返回值得时候出现yield就变成生成器,而不是函数了

面向对象

魔法方法

init:对象初始化方法

new:创建对象时候执行的方法,单列模式会用到

str:当使用print输出对象的时候,只要自己定义了str(self)方法,那么就会打印从在这个方法中return的数据

del:删除对象执行的方法

init v.s. new

super

装饰器

  • @property

乱七八糟

出自 https://zhuanlan.zhihu.com/p/54430650

版本区别

python2和python3区别?列举5个

1、Python3 使用 print 必须要以小括号包裹打印内容,比如 print('hi')

Python2 既可以使用带小括号的方式,也可以使用一个空格来分隔打印内容,比 如 print 'hi'

2、python2 range(1,10)返回列表,python3中返回迭代器,节约内存

3、python2中使用ascii编码,python中使用utf-8编码

4、python2中unicode表示字符串序列,str表示字节序列

python3中str表示字符串序列,byte表示字节序列

5、python2中为正常显示中文,引入coding声明,python3中不需要

6、python2中是raw_input()函数,python3中是input()函数
python2.x中input()和raw_input()都存在
raw_input():接受任何类型的输入,返回的对象类型为字符串
input():等价于eval(raw_input()),它希望读取一个合法的python表达式,所以当输入字符串时,需要给输入的内容添加单/双引号。此外,python2.x中input()具有一个特性:当输入的类型为数字时,返回的对象类型也为数字。

python3.x中,只有input()函数
input():接受任何类型的输入,返回的对象类型为字符串。

运行效率

提高python运行效率的方法

1、使用生成器,因为可以节约大量内存

2、循环代码优化,避免过多重复代码的执行

3、核心模块用Cython PyPy等,提高效率

4、多进程、多线程、协程

5、多个if elif条件判断,可以把最有可能先发生的条件放到前面写,这样可以减少程序判断的次数,提高效率

多进程多线程的效率问题

进程:

1、操作系统进行资源分配和调度的基本单位,多个进程之间相互独立

2、稳定性好,如果一个进程崩溃,不影响其他进程,但是进程消耗资源大,开启的进程数量有限制

线程:

1、CPU进行资源分配和调度的基本单位,线程是进程的一部分,是比进程更小的能独立运行的基本单位,一个进程下的多个线程可以共享该进程的所有资源

2、如果IO操作密集,则可以多线程运行效率高,缺点是如果一个线程崩溃,都会造成进程的崩溃

应用:

IO密集的用多线程,在用户输入,sleep 时候,可以切换到其他线程执行,减少等待的时间

CPU密集的用多进程,因为假如IO操作少,用多线程的话,因为线程共享一个全局解释器锁,当前运行的线程会霸占GIL,其他线程没有GIL,就不能充分利用多核CPU的优势

列举3条以上PEP8编码规范

1、顶级定义之间空两行,比如函数或者类定义。

2、方法定义、类定义与第一个方法之间,都应该空一行

3、三引号进行注释

4、使用Pycharm、Eclipse一般使用4个空格来缩进代码

无关

10个Linux常用命令

ls pwd cd touch rm mkdir tree cp mv cat more grep echo

写5条常用sql语句

show databases;

show tables;

desc 表名;

select * from 表名;

delete from 表名 where id=5;

update students set gender=0,hometown="北京" where id=5

列出常见的状态码和意义

200 OK

请求正常处理完毕

204 No Content

请求成功处理,没有实体的主体返回

206 Partial Content

GET范围请求已成功处理

301 Moved Permanently

永久重定向,资源已永久分配新URI

302 Found

临时重定向,资源已临时分配新URI

303 See Other

临时重定向,期望使用GET定向获取

304 Not Modified

发送的附带条件请求未满足

307 Temporary Redirect

临时重定向,POST不会变成GET

400 Bad Request

请求报文语法错误或参数错误

401 Unauthorized

需要通过HTTP认证,或认证失败

403 Forbidden

请求资源被拒绝

404 Not Found

无法找到请求资源(服务器无理由拒绝)

500 Internal Server Error

服务器故障或Web应用故障

全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务