python基础语法

本文总结了一些细节性的语法知识


__init__的作用:

  1. Python中package的标识,不能删除

  2. 定义__all__用来模糊导入:
    __init__文件中:__all__ = [“模块名”,“函数名”,“变量名”]

    from 模块 import * 会从__all__中逐个导入

  3. 批量导入外部目录的包

  • 在__init__文件中:
    import os
    imoprt sys
  • 在所需引用的文件中:
    import __init__所在的包名 as na
    想使用init的包需要在包前加入命名空间na
  1. 定义类时,相当于构造函数,自动调用forward的函数

    super(ConvBNLayer, self).__init__() 
    #父类对象调用自已的init函数,来初始化子类
    #父类的__call__会调用forward
    

参数类型

  • *args表示可变参数(元组) ps:*的作用:1.函数实参,2.序列解包
  • **kwargs表示关键字参数(字典)

惰性序列(迭代器):

迭代至某个元素才会去计算,节省了内存资源

list与array:

  • list的元素类型不必相同,但需存储指针与元素类型;array的元素类型必须相同

range与np.arange:

  • range返回类型range,可用于迭代;arange返回类型numpy.ndarray,且步长可以是小数,可用于向量使用

zip:

  • zipped=zip(a,b)打包;a,b=zip(*zipped)解包

eval与ravel、flatten:

  • ravel()与flatten()都是将多维数组降为一维,其中flatten()不会对原矩阵产生影响;eval()执行字符串表达式并返回值

判值或判指向

  • x == y #两引用对象是否有相同值
  • x is y #两引用是否指向同一对象

os与sys:

__file__获取当前脚本路径

  • os.system()运行命令

  • os处理文件

      • os.mkdir()创建单个目录
      • os.makedirs()创建多级目录
      • os.remove 删除一个文件
      • os.removedirs删除多个文件夹
      • os.renames(old,new)递归重命名目录或文件

      • os.path.split()分离文件名,返回两个值
      • os.path.splitext()分离扩展名,返回两个值
      • os.path.join(dir,filename)拼接目录名和文件名
      • os.getcwd()获取所在文件夹路径
      • os.listdir返回指定目录下的所有文件和文件夹

      • os.path.abspath()获取文件的绝对路径
      • os.path.realpath()获取文件的绝对路径(这是快捷方式对应文件的路径,而非软链接所在的路径)
      • os.path.basename()获取文件名称
      • os.path.dirname()获取所在文件夹路径,可嵌套使用
      • os.path.isfile()检验路径是否为文件
      • os.path.isdir()检验路径是否为文件夹
      • os.path.exists()检验路径是否真实存在
  • sys.path获取列表形式的文件路径、sys.argv获取脚本参数


读写文件

将内容写入文件中:

方法一:

print('test1','test2',2022,sep='\n',file=open('hello.txt','w',encoding='utf-8'))

方法二:

import json
filename = "infos.jsonl" #jsonl格式可每行存储字典
with open(filename, 'a', encoding='utf-8') as f:
    json.dump(data_json, f, ensure_ascii=False)
    f.write('\n')

读取文件并整体输出:

def read_file(filename):
  # with可以自动释放缓存
  with open(filename,'r',encoding='utf-8')as f:
    content=f.readlines()
    print(content)

序列化pickle与json

  • api
    • dump写入文件
    • dumps生成序列化字符串
    • load文件加载
    • loads把序列化的字符串反向解析
  • 不同
    • json --> 实现Python数据类型与通用(json)字符串之间的转换
      所有语言都支持
      只支持常规数据类型,如str、int、tuple、list、set、dict
    • pickle --> 实现Python数据类型与Python特定二进制格式之间的转换
      支持python
      支持py的所有数据类型

json序列化

数据类型对应关系

PythonJson
dictObject
list,tuplearray
strstring
int,float,int-numbers
Truetrue
Falsefalse
Nonenull
PythonJson
Objectdict
arraylist
stringstr
number(int)int
number(real)float
trueTrue
falseFalse
nullNone

注意自定义的数据类型需要转换:

  • 序列化:Python对象 --> dict --> JSON object

  • 反序列化:JSON object -> dict --> Python对象

#序列化
#indent缩进:JSON的array元素和object成员会以相应的缩进级别进行打印输出
#separators的值必须是tuple,通过赋值(',',':')来消除空白字符
#ensure_ascii设置为False,中文可显示
import json
a=json.dumps({'a': '中国 ', 'c': True, 'e': 10, 'b': 11.1, 'd': None, 'f':[1, 2, 3], 'g': (4, 5, 6)},sort_keys=True,separators=(',',':'),ensure_ascii=False)
print("a:",a)
#反序列化
b=json.loads(a)
print("b:",b)

#序列化到文件中
with open('test.json', 'w') as fp:
    json.dump({'a': 'str中国', 'c': True, 'e': 10, 'b': 11.1, 'd': None, 'f': [1, 2, 3], 'g': (4, 5, 6)}, fp,indent=4)
#反序列化文件中的内容
with open('test.json', 'r') as fp:
    print(json.load(fp))

pickle序列化

import pickle
text = {'a':'str', 'c': True, 'e': 10, 'b': 11.1, 'd': None, 'f': [1, 2, 3], 'g':(4, 5, 6)}
#序列化
a = pickle.dumps(text)
print(a)
#反序列化
b = pickle.loads(a)
print(b)

#持久化到文件
with open('pickle.txt', 'wb') as f:
    pickle.dump(text , f)
# 从文件中读取数据
with open('pickle.txt', 'rb') as f:
    b = pickle.load(f)
    print(b)
...

详见:https://www.cnblogs.com/yyds/p/6563608.html

参数解析

import argparse
parser = argparse.ArgumentParser() # 初始化解析器
parser.add_argument("--picture",default='a',help="图片名") # 值不能用单引号, 参数名称可不全输入,但区分大小写
parser.add_argument("-image",default='b', help="图片名")   # 当-i和--image同时存在的时候,只会有args.image而没有args.i
parser.add_argument("abc",default='c', help="图片名") # 位置参数,[不需要写参数名称,参数输入的顺序必须与程序中定义的顺序一致]
args = parser.parse_args() # 解析参数
args.pic=1 #会新增pic参数
args.abc=3 #命令行必须要有参数 

–与-的异同之处:

  • 相同点:

    ​ ==–与-==的值不能用单引号, 参数名称可不全输入形如:--pic aa,但区分大小写

  • 不同点:

    ​ 当==–image和-i==同时存在的时候,只能args.image而不能args.i

优先级

  1. args.picture = aaa 参数名称必须输全
  2. 命令行参数
  3. default字段值

pip库用法

自行安装:

从官网上(https://bootstrap.pypa.io/get-pip.py)直接下载get-pip.py,然后直接运行python get-pip.py脚本即可

增删升查:

  • pip install package-name

    • 下载不安装:pip download package_name -d "path"

    • 指定国内源安装:pip install -i https://pypi.douban.com/simple/ package_name

    • 批量安装:pip install -r requirements.txt

    • 生成已安装的库包:pip freeze > requirements.txt

    • 打包:pip wheel package-name

  • pip uninstall package_name

  • pip install -U package_name

  • pip show -f package_name

    • 查看版本兼容问题:pip check
    • 查看已安装的库包:pip list

国内源:

清华:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
华中理工大学:http://pypi.hustunique.com/
山东理工大学:http://pypi.sdutlinux.org/ 
豆瓣:http://pypi.douban.com/simple/

collections库用法

a=[10, 10, 12, 12, 10, 13, 13, 14]
# 统计列表中元素的频率
print(dict(collections.Counter(a))) #{10: 3, 12: 2, 13: 2, 14: 1}

# 创建
iterable1 = [10, 10, 12, 12, 10, 13, 13, 14]
iterable2 = [10, 14, 14, 14, 14, 14]
counter1 = collections.Counter(iterable1) # Counter({10: 3, 12: 2, 13: 2, 14: 1})
counter2 = collections.Counter(iterable2) # Counter({14: 5, 10: 1})
print(counter1)
print(counter2)
print('key出现频次:', counter1[10]) # key出现频次
print('返回n个出现频次最高的元素和其对应出现频次:', counter1.most_common(2))
# counter加减
print(counter1+counter2)
print(counter1-counter2)
# 检查两个字符串的组成元素是否相同
print(collections.Counter(iterable1) == collections.Counter(iterable2))

loguru库用法

下载并导入

pip install loguru
from loguru import logger

使用add() 方法对logger 进行简单的配置:

logger.add('runlog.log', encoding='utf-8')
logger.add("runtime_{time}.log", rotation="10 MB", encoding='utf-8')  # 文件过大于10M就会重新生成一个文件
logger.add("test_4.log", retention="5 days", encoding='utf-8')  # 只保留最近五天的日志文件
logger.add("test_5.log", compression="zip", encoding='utf-8')    # 以zip格式对日志进行保存

根据等级写入日志

logger.debug("debug message")
logger.info("info level message")
logger.warning("warning level message")
logger.error("error level message")
logger.critical("critical level message")

https://zhuanlan.zhihu.com/p/514838075

元类

	# property装饰器用于将被装饰的方法伪装成一个数据属性,在使用时可以不用加括号而直接引用
    class PersonInfo:
        def __init__(self, name, sex):
            self.name = name
            self.sex = sex
        # 默认生成实例方法,输入参数至少有一个:实例对象self
        # @classmethod 类方法,输入参数至少有一个:类本身cls
        # @staticmethod 类静态方法,无法调用任何类属性和类方法,就是普通方法        

numpy

返回前N大数及其索引np.partitionnp.argpartition

import numpy as np

a_list = [7, 10, 12, 0, 6, 8, 9, 1, 16, 4, 6, 100]
a_array = np.array([7, 10, 12, 0, 6, 8, 9, 1, 16, 4, 6, 100])

index_big = np.argpartition(a_list, -3)[-3:]
print('前k大元素索引:', np.argpartition(a_list, -3)[-3:])
print(a_array[index_big])
print('前k小元素索引:', np.argpartition(a_list, 3)[:3])
print('-------------------------------')
print('前k大元素:', np.partition(a_array, -3)[-3:])
print('前k小元素:', np.partition(a_array, 3)[:3])

返回满足特定条件的元素索引where

y = np.array([1, 5, 6, 8, 1, 7, 3, 6, 9]) 
print(y[np.where(y > 5)])
print(np.where(y > 5, "Hit", "Miss")) #['Miss' 'Miss' 'Hit' 'Hit' 'Miss' 'Hit' 'Miss' 'Hit' 'Hit']

operator

用符号代替函数

import operator
# add,sub这些函数入参只有两个
action = {
    "+": operator.add,
    "-": operator.sub,
    "/": operator.truediv,
    "*": operator.mul,
    "**": pow
}
print(action['/'](50, 5))  # 25
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值