Python-- pen questions

First, how to improve the operating efficiency of Python:

1, using the generator, as can save a lot of memory

2, code optimization cycle, to avoid excessive repetition code execution

3, the core module Cython PyPy the like, to improve efficiency

4, multi-process, multi-thread, coroutine

5, a plurality of judgment if elif conditions, the conditions can be most likely to occur to the front write, thus reducing the number of times the program determines, to improve efficiency.

Second, the example instructions zip function:

list1 = [1,3,5]

list2 = [2,4,6]

zipped = zip(list1, list2)

print(list(zepped)) # [(1,2),(3,4),(5,6)]

print(list(zip(*zipped)) # [(1,3,5),(2,4,6)]

Third, intended to illustrate abnormalities associated modules try except else finally the

try..except..else没有捕获到异常,执行else语句

try..except..finally不管是否捕获到异常,都执行finally语句

四、logging模块的使用?

 

import logging
logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

logger.info("Start print log")
logger.debug("Do something") logger.warning("Something maybe fail.") logger.info("Finish")

 

 Five, a = (1,) b = (1), c = ( "1") What are the types of data?

print(type((1, ))) # tuple
print(type((1))) # int
print(type(("1"))) # str

六、统计字符串每个单词出现的次数
from collections import Counter
s3 = "kjalfj;ldsjafl;hdsllfdhg;lahfbl;hl;ahlf;h"
print(Counter(s3))

Seven, Python three head operations:
# 若果 a>b 成立  就输出  a-b  否则 a+b
h = a-b if a>b else a+b
八、例举五条PEP8 规范例举五条PEP8 规范:
不要在行尾加分号, 也不要用分号将两条命令放在同一行
不要使用反斜杠连接行
不要在返回语句或条件语句中使用括号
顶级定义之间空2行, 方法定义之间空1行,顶级定义之间空两行
如果一个类不继承自其它类, 就显式的从object继承

Nine, object-oriented briefly in __new__ and __init__ difference?
1、__new__至少要有一个参数cls,代表当前类,此参数在实例化时由Python解释器自动识别。
2、__new__必须要有返回值,返回实例化出来的实例,这点在自己实现__new__时要特别注意,可以return父类(通过super(当前类名, cls))__new__出来的实例,或者直接是object的__new__出来的实例。 3、__init__有一个参数self,就是这个__new__返回的实例,__init__在__new__的基础上可以完成一些其它初始化的动作,__init__不需要返回值。 4、如果__new__创建的是当前类的实例,会自动调用__init__函数,通过return语句里面调用的__new__函数的第一个参数是cls来保证是当前类实例,如果是其他类的类名,;那么实际创建返回的就是其他类的实例,其实就不会调用当前类的__init__函数,也不会调用其他类的__init__函数。
十、谈下Python的GIL?
GIL是Python的全局解释器锁,同一进程中假如有多个线程运行,一个线程在运行Python程序的时候会霸占Python解释器(加了一把锁即GIL),使该进程内的其他线程无法运行,等该线程运行完后其他线程才能运行。如果线程运行过程中遇到耗时操作,则解释器锁解开,使其他线程运行。所以在多线程中,线程的运行仍是有先后顺序的,并不是同时进行。
多进程中因为每个进程都能被系统分配资源,相当于每个进程有了一个Python解释器,所以多进程可以实现多个进程的同时运行,缺点是进程系统资源开销大。

十一、Python2和Python3的range(100)的区别?

Python2返回列表,Python3返回迭代器,节约内存。
 

Guess you like

Origin www.cnblogs.com/pythonbetter/p/11992467.html