你需要改掉的Python开发习惯(四)

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值