Python常用小技巧
前言
在平时编写Python代码时,有许多实用的小技巧,本文实例展示了一些常用的小技巧,分享给大家供大家参考。
提示:以下是本篇文章正文内容,下面案例可供参考。
一、自动检测并安装某个三方数据库
python 3.0以上的版本都自带默认安装了pip,我们可以通过调用os来自动检测并安装一些python三方数据库。
import os
def install_database():
""" 自动检测并安装数据库 """
try:
import pandas as pd
import requests
import matplotlib
import numpy
pd_version = pd.__version__
requests_version = requests.__version__
matplotlib_version = matplotlib.__version__
numpy_version = numpy.__version__
except:
print("您的电脑缺少必要的数据, 正在自动安装, 请稍等...")
os.popen(cmd="pip install -i https://pypi.doubanio.com/simple/ pandas").read()
os.popen(cmd="pip install -i https://pypi.doubanio.com/simple/ requests").read()
os.popen(cmd="pip install -i https://pypi.doubanio.com/simple/ matplotlib").read()
os.popen(cmd="pip install -i https://pypi.doubanio.com/simple/ numpy").read()
print("自动安装完成!")
else:
print(f"电脑已安装 pandas 数据库, 版本:{pd_version}")
print(f"电脑已安装 requests 数据库, 版本:{requests_version}")
print(f"电脑已安装 matplotlib 数据库, 版本:{matplotlib_version}")
print(f"电脑已安装 numpy 数据库, 版本:{numpy_version}")
return
if __name__ == '__main__':
install_database()
二、自动显示程序所执行的时间
当我们想知道自己编写的程序运行需要多少时间才能完成时,可以使用下面的技巧实现。
import time
start_time = time.time() # 记录程序开始时间
# 主程序
for x in range(101):
print(f"{x}%", end="\r") # 实时打印进度显示
time.sleep(0.1)
end_time = time.time() # 记录程序结束时间
print(f"经历的时间:{int(end_time - start_time)}s")
三、input() 一次性输入多个值
# 对于确定数值输入时
x1, x2 = input("请输入:").split(',')
y1, y2 = map(str, input("请输入:").split(','))
x1, x2 = x1.strip(), x2.strip()
# 对于不确定数值输入时
list_x = list(map(str, input("请输入:").split(',')))
list_x = [x.strip() for x in list_x]
print(list_x)
四、查询某个对象内存占用的情况
import sys
list_x = list(range(1000))
print(sys.getsizeof(list_x), "byte") # 单位是byte
五、查询某个文件的内存占用的情况
import os
print(os.path.getsize("test.py"), "byte") # 单位是byte
六、多个字典合并
dict_1 = {"kevin": [1, 2, 3], "jack": [4, 5, 6]}
dict_2 = {"kevin": [11, 12, 3]}
dict_3 = {"denis": [11, 12, 3]}
dict_4 = {"leo": [11, 12, 3]}
# 方法一:
dict_all = {**dict_1, **dict_2, **dict_3, **dict_4} # 新的相同键值会覆盖原键值
print(dict_all)
# 方法二:
dict_all = {}
dict_all.update(dict_1)
dict_all.update(dict_2)
dict_all.update(dict_3)
dict_all.update(dict_4)
print(dict_all)
七、检查某个文件夹是否存在, 如果不存在就创建它
import os
def check_folder(folder_name):
""" 检查某个文件夹是否存在, 如果不存在就创建它 """
try:
os.listdir(folder_name)
except:
os.mkdir(folder_name)
else:
print("文件夹存在!")
return
if __name__ == '__main__':
check_folder(folder_name="shusheng")
八、两个列表转换为一个字典
list_1 = ['a', 'b', 'c', 'd']
list_2 = [11, 22, 33, 44]
# 方法一:
dict_1 = {key: value for key, value in zip(list_1, list_2)}
print(dict_1) # 打印结果: {'a': 11, 'b': 22, 'c': 33, 'd': 44}
# 方法二:
dict_1 = dict(zip(list_1, list_2))
print(dict_1) # 打印结果: {'a': 11, 'b': 22, 'c': 33, 'd': 44}
九、检查某个元素在列表中出现的概率
list_1 = [1, 2, 3, 4, 2, 1, 3, 4, 4, 4]
print(f"统计4在列表出现的概率: {(list_1.count(4) / len(list_1)) * 100} %")
十、列表元素的进制转换
a = ['0x000003ff', '0x000003f9']
b = [bin(int(x, 16))[2:] for x in a] # 十六进制转二进制
print(b)
c = [oct(int(x, 16))[2:] for x in a] # 十六进制转八进制
print(c)
d = [int(x, 16) for x in a] # 十六进制转十进制
print(d)
w = ['199', '188']
x = [bin(int(x))[2:] for x in w] # 十进制转二进制
print(x)
x = [oct(int(x))[2:] for x in w] # 十进制转八进制
print(x)
x = [hex(int(x))[2:] for x in w] # 十进制转十六进制
print(x)
十一、“九九乘法表”
for x in range(1,10,1):
for y in range(1,x+1,1):
print(f"{x}x{y}={x*y}", end = '\t')
print()
十二、创建一个有序的字典
# 调用pyton内置模块创建一个有序的字典
from collections import OrderedDict
list1 = OrderedDict()
list1['kevin'] = 'moshell'
list1['shusheng'] = 'python'
list1['jack'] = 'moshell'
list1['tony'] = 'java'
print(list1)
for key, value in list1.items():
print(key, ':', value)
感谢您的阅读!
Python是一种非常多样且适合开发的语言,其实还有更多我不知道的技巧。
如果您有兴趣,请在下面留言,分享你自己最喜欢的Python技巧!