Python101

xiaoxiao2021-02-28  136

Python101

单双引号不分命名区分大小写BIF buildInFunction 内置函数 dir()注释 “”“explain here”“”import sys; sys.path 查看py模块python3 idle窗口运行python 主命名空间 main()数据为元组,tupe,不可变数据,[]为可变数据缩进来写代码块,必须严格执行数组读取 a[0:3]

列表

列表CRUD

高层集合 可以混合各种数据列表类似于数组,不需要刻意声明数据类型

创建列表 cast = ["a",'b','c'] print(len(cast)) cast[1]

.append('a') 末尾加一 .extend('a','b') 末尾加多 .pop() 提取末尾 .remove('a') 删指定 .insert(0,'a') 插入指定index,后续index值向后移

迭代 for…in…

for item in items: print(item)

while … :

等同于上迭代

count=0 while count < len(cast): print(cast[count]) count = count+1

列表嵌套

列表内可以随意嵌套 创建3层迭代

movie = ['a',1,'b',2,'c',3,['a1','a2',['b1','b2']]] print(movie[6][2][1]) //b2

用for-in 会只迭代第一层 for item in movie: print (item) // a ... 3 ['a1', 'a2', ['b1', 'b2']] 迭代3层,用if:...else:和isinstance(a,list)检测是否含有子列表。

isinstance(item,list) 检测类型,内置BIF,list为类型

for item in movie: //检测第一层 if isinstance(item,list): //第二层 for item_0 in item: if isinstance(item_0,list): //第三层 for item_1 in item_0: print (item_1) else: print(item_0) else: print (item)

def 创建函数

如果检测到item为list,则调用这身函数

def loop(the_list): for item in the_list: if isinstance(item,list): loop(item) else: print(item)

print_loop 接受列表,以及通过空格显示列表层数,默认设置为false

def print_loop(the_list, indent=false, level=0) for item in the_list: if isinstance(item, list): print_loop(item, indent, level+1) else: if indent: for tab in range(level): print("\t", end="") //end="" 后面加个空格 print(item)

运行py代码,py模块的创建和导入

把函数写在.py的文件中,为模块。 在idle中两种导入方式:

通过现成路径中导入 import sys; sys.path 查看目前路径,并在在路径中添加 hello.py import hello 导入 hello.loop(movie) 使用函数,

引入模块 以hello.loop(...)引用函数 或者import loop from hello引入到当前命名空间

打包发布 distribution

创建hello文件夹,添加 hello.py, setup.py 在hello文件下,终端运行: python3 setup.py sdist 构建发布文件 sudo python3 setup.py install 将发布安装到python本地副本中 import hello 导入

安装后目录结构 p69

hello | |__manifest //包含文件列表 | |__build | |__llb | |__hello.py //代码 |__dist | |__apple-1.0.0.tar.gz //发布包 | |__apple.py //代码 | |__apple.pyc //‘编译’版本的代码 | |__setup.py //元数据

上传到PyPl

数据读写

python读取机制

读取txt文件 打印

import os os.getcwd() //当前目录 os.chdir('../a/b') //切换目录 data = open('sketch.txt') //打开 print(data.readline(), end="") //打印单行 data.seek(0) //指针会到起点 for item in data: print(data, end="") //打印每一行 data.close() //关闭

分解数据 find split

find(:)==-1 查找 (role,words) = item.split(":",1) split分开,两部分

role = [] words = [] try: data = open('sketch.txt') for each_line in data: try: //if not each_line find(':') == -1: (role, words) = each_line.split(":",1) //返回不可变数据 print(role) print('said:said',end="") print(words) except ValueError pass data.close() except IOError: print('data has been missing') ...

写入模式,访问模式

open("date.out",w), 写,清空文件,或者新建。 ..., w+ 打开文件读写,或者新建。

把保存放在finally: ,确保一定会保存,否则try中出现错误,数据丢失。 print(role, file=man_file) 把数据写入

使用try/except/finally模式 ... try: man_file = open('man_data.txt',w) //w读取模式,新建文件 other_file = open('other_data.txt',w) print(role, file = man_file) //用print写入数据 print(words, file = other_file) except IOError as err: print('File error:' + str(err)) //详细定制错误,把IOError转化为str字符串,打印 finally: man_file.close() //close 关闭保存 other_file.close()

if 'data' in locals(): 用locals检查当前作用域中的所有名

或者with模式,替代手动关闭 open/clsoe, with/as context manager 自动在结尾管理对象 file = open('foo.txt') ... close(file) with open('foo.txt') as file: ... try: with open('man_data.txt',w) as man_file, open('other_data.txt',w): as other_file: print(role, file=man_file) print(words, file = other_file)

函数中添加文件保存

引入sys.stdout 模块,保存为标准输出

def print_lol(the_list, indent=False, level=0, fn=sys.stdout) for each_item in the_list: if isinstance(each_item, list): print_lol(each_item, indent, level+1, fn) else: if indent: for tab_stop in range(level): print("\t", end="", file=fn) print(each_item, file=fn)

pickle内置数据库 dump/load

内部保存数据,二进制模式:'wb','rb' dump 和load 读取存储

import pickle a_list = [] ... with open ('mydata.pickle', 'wb') as mysavedata: //二进制写入wb模式打开 pickle.dump([1,2,'three'], mysavedata) //pickle.dump储存 with open ('mydata.pickle', 'rb') as myrestoredata: //二进制读取rb模式打开 a_list = pickle.load(myrestoredata) //pickle.load读取 print a_list

处理数据

data.strip().split(',') 方法串链 method chaining 左到右 - 先strip()把数据空白去掉 - 在split(',') 进行分割

print(sotred(james)) 函数串链 funciton chaining 右到左

数据处理函数

sort() 原地排序 sorted() 创建副本 排序

推导列表 list comprehension 减少列表a到列表b的转换

name= [ interation for item in items] p181

mins = [1,2,3] secs = [ m*60 for m in mins] clean_mikey=[] for each_t in mikey: clean_mikey.append(sanitize(each_t))

简写成 clean_mikey = [sanitize(each_t) for each_t in mikey]

集合 不允许重复值

set() print(sorted(set([sanitize(t) for t in sarh]))[0:3]) 输出前3,集合去重

字典 key/value

cless={} 或者 pain = dict()

定义类 class

使用class创建对象, 包含__init__特殊方法,如何初始化对象 self用于分辨对象 Athlete().__init__(a)

class Athlete: def __init__(self, a_name, a_dot=None, a_time=[]): self.name = a_name self.dob = a_dob self.times = a_times def how_bif(self)

json格式

import json names = ['a','b',['asd','ads'],'d'] to_transfer = json.dump(names) //将列表转化为json from_transfer = json.load(to_transfer) //将json转化为列表

数据库 内置sqlite3数据库管理系统

import sqlite3 connection = sqlite3.connect('test.sqlite') //建立连接 cursor = connection.cursor //创建游标 cursor.execute("""SELECT DATA('now')""") //操作 connection.commit() //执行 关闭 connection.close()
转载请注明原文地址: https://www.6miu.com/read-77740.html

最新回复(0)