1、怎么去创建自己的索引计数器变量:
def create_index_counter():
l = [1, 2, 3]
i = 0
for x in l:
# do some operations
i += 1
其实你可以用enumerate来直接获取对应的枚举:
def create_index_counter():
l = [1, 2, 3]
for i, x in enumerate(l):
# do some operations
2、使用time.time():
import time
def do_time():
start = time.time()
time.sleep(1)
end = time.time()
print(end - start)
但事实是用time.perf_counter()的精度要高于time.time(),因为perf_counter具有最高可用分辨率的时钟。
import time
def do_time():
start = time.perf_counter()
time.sleep(1)
end = time.perf_counter()
print(end - start)
3、打印语句print与日志记录模块logging的对比:
def print_vs_logging():
print("debug info")
print("just some info")
print("bad error")
一般都会使用日志功能,因为可以设置日志的打印等级,来控制哪些类型的日志需要输出。
import logging
def print_vs_logging():
logging.debug("debug info")
logging.info("just some info")
logging.error("bad error")
def main():
level = logging.DEBUG
fmt = '[%(levelname)s] %(asctime)s - %(message)s'
logging.basicConfig(level = level, format=fmt)
print_vs_logging()
4、对子进程库中的任何函数使用"shell=True":
def function():
subprocess.run(["ls -l"], capture_output=True,shell=True)
建议是去掉"shell=True"
具体原因也可以参考该文章:http://www.zzvips.com/article/197970.html
def function():
subprocess.run(["ls", "-l"], capture_output=True)
5、用python做数学运算:
def to_sum():
x = list(range(10))
y = list(range(10))
sum = [a + b for a, b in zip(x, y)]
其实可以使用numpy模块去做同样的计算:
import numpy as np
def to_sum():
x = np.arange(10)
y = np.arange(10)
sum = x + y