python 关键字
具有特殊功能的标识符称为关键字,35个
import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break',
'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not',
'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
常用数据类型6个
Number(数字):int、float、bool、complex(复数)
String(字符串):字符串不可变,操作后产生新的字符串
List(列表)
Tuple(元组): 不能被修改
Set(集合):不重复且无序,
Dictionary(字典)
number
type(a) # 查类型
isinstance(a,int) # 判断是否是这个类型
字符串
字符串操作:删除(去空格)、string替换和连接、查找、比较、截取和翻转、 大小写转换、字符串判断、 分割split()
, 拼接join()
、输出格式
-
去空格及特殊符号 : s.strip()=lstrip()+rstrip()
s.strip() # 删除开头、结尾的空格或者其他想删的字符 s.lstrip() # 删除开头的空格 s.rstrip('e') # 删除尾部的e
-
将字符串前n个字符替换为指定的字符,连接字符串
+
str1 = '12345' ch = 'r' n = 3 str1 = n * ch + str1[3:] #'rrr45'
-
查找字符: find() / index()
区别,若找不到,前者返回-1,后者报错s="I am good" index=s.find("I") # 返回该字符出现的第一个位置 index=s.index("7") # index(位置)返回该位置的字符,否则报错 s.index('g') # index(字符) 找得到返回0,找不到报错
-
比较字符串, is、==和>、<
a='ff' b='ff' a is b # true, 但是判断数字相等不要用 is 操作符 a == b # true a is not b #false a != b # false
1.有时候两个字符串打印出来看着一样,但是判断却是False?
有 回车‘\n’,所以需要.strip()
2.有时候==判断是 True ,is 判断却是 False?
这是因为两个字符串来自不同的内存块,内存地址不一样。id() 函数用于获取对象的内存地址。id(s1) == id(s2)
-
字符串截取和翻转 []
a=0123456789 # 字符串的截取[首位:末尾:步长] a[1:4:2] # 1,3 a[::-1] # 9876543210
-
大小写转换
s='advBVOB' s.lower() #小写 s.upper() #大写 s.swapcase() #大小写互换 'ADVbvob' s.capitalize() #首字母大写
-
字符串判断
str.isalnum() # 判断所有字符都是数字或者字母 str.isalpha() # 判断所有字符都是字母 str.isdigit() # 判断所有字符都是数字 str.islower() # 判断所有字符都是小写 str.isupper() # 判断所有字符都是大写 str.istitle() # 判断所有单词都是首字母大写,像标题 str.isspace() # 判断所有字符都是空白字符、\t、\n、\r print("A123".startswith("A")) # 判断是否以A为开头 print("A123".endswith("A")) # 判断是否以A为结尾
-
分割
split()
, 拼接join()
(字符串和list互相转换, )a="我今天,不上班" # 我今天,不上班 b=a.split(',') # ["我今天","不上班"] c="".join(b) # 我今天不上班 str = "-"; d=str.join(c); # 我-今-天-不-上-班
-
输出格式
format
, 以及对齐a="你是{}".format("猪") S.ljust(width,[fillchar]) #输出width个字符,S左对齐,不足部分用fillchar填充,默认的为空格。 S.rjust(width,[fillchar]) #右对齐 S.center(width, [fillchar]) #中间对齐 S.zfill(width) #把S变成width长,并在右对齐,不足部分用0补足
List
-
赋值 + * =,新建全是0的数组
a=[1,2] b=[2,3] c=a+b #[1,2,2,3] d=a*2 #[1,2,1,2] # 新建二维数组 arr=[[0 for i in range(N)] for i in range(M)]
-
列表插入 .insert() ,扩展 .extend(), 删除 .remove() .pop() .clear() del
name1=['John','Tony'] name1.insert(0,"Alex") # ['Alex','John','Tony'] name2=['aa','bb','cc'] name1.extend(name2) # 相当于+ ,['Alex', 'John', 'Tony', 'aa', 'bb', 'cc'] name1.extend('abc') # ['John', 'Tony', 'a', 'b', 'c'] name1.remove("aa") # 删除指定,只能删除一个”aa“ name1.pop() # 弹出最后一个"cc",但是也可指定删除某一个 name1.clear() # [],删除元素,list还在 del name1 # 整个list删除,print name1会报错
-
copy
浅copy–>如果直接copy,且list里面有可变的值,比如里面套list,那么,该可变部分,副本会随原本变动s=["123"] a=[1,2,3,s] b=a.copy() # [1, 2, 3, ['123']] s.append("666") print(a) # [1, 2, 3, ['123', '666']] print(b) # [1, 2, 3, ['123', '666']]
深copy
from copy import deepcopy s=["123"] a=[1,2,3,s] b=a.deepcopy() # [1, 2, 3, ['123']] s.append("666") print(a) # [1, 2, 3, ['123', '666']] print(b) # [1, 2, 3, ['123']]
-
排序 .sort()、 sorted(a) 、.reverse()
a.sort() #改原数组 b=sorted(a) #不改原数组 a.reverse() #倒序
元组 tuple
tuple = 由1个或多个被逗号隔开的值,所以:a=‘123’, → type(a)=tuple
-
转换
a='123' tuple(a) # ('1', '2', '3')
-
元组只能查询 .count,.index(),删除整个元组 del
a.count(1) # 查找元素出现次数
del a
字典
字典的key值是不可以重复的,如果重复默认取最后度一个value值。
-
新建 .fromkeys(“123”),增 .update(),查 in
{}.fromkeys("123") # 给定key值新建 {'1': None, '2': None, '3': None} #fromkeys的value都是统一的 d.update({'c':cc,'d':dd}) # 增加 d.get('c') # cc 'd' in d # True
-
已有dict,增加key or value
dict={} list=[1,2,3] list2=[4,5,6] dict["B"]=[list] dict["B"].append(list2) # dict={"B":[[1,2,3],[4,5,6]]}
-
删 .pop(‘a’) 、 .popitem() 、clear()、del
d.pop('a') # 删 d.popitem() # 删最后一个 d.clear() # 清空{} del d['b'] # 删除字段
-
输出 key,value
d.keys() #所有key,是一个list d.values() d.items() #取字典所有元素,[('a','aa'),('b','bb')...](list套tuple)
-
转换
a=('name','age') b=('xiaoming','20') dict(zip(a,b)) # {'name':'xiaoming','age':'20'}
操作文件
文件地址:C:\Users\Bingo\PycharmProjects 不可直接用
- 再加斜杠:C:\Users\Bingo\PycharmProjects (因为反斜杠是转义符)
- 将反斜杠改成正斜杠:C:/Users/Bingo/PycharmProjects
- 最前面加r: r”C:\Users\Bingo\PycharmProjects“
第一种 open
file = open( r"C:\Users\Bingo\PycharmProjects\python-test\test2.txt","w")
#如果报错中,有 'gbk',那么加一个 encoding="utf-8"
#print(file.read())
file.write("hello world")
file.close() # 必要
第二种 open,不用close
with open(r"test2.txt","r") as file:
a=file.readlines() #行末有\n
a=''.join(line).strip('\n').splitlines()
print(file.tell()) #返回游标在哪行
#''.join(line)->变str,才能用strip,splitlines()->变回list
覆盖写入
with open(r"last_time.txt", "w") as file:
file.write("dwefewf")
不覆盖写入,追加
with open(r"last_time.txt", "a") as file:
file.write("dwefewf")
os操作
import os
b=os.getcwd() #得到当前路径
if not os.path.exists("test") # 判断该文件夹存不存在
os.makedirs("test") # 创建文件夹
os.system("cd / && python test.py") # 操作终端, && 连接2个操作
内置函数
-
eval()
方法参考 :字符串对象转换为能够具体的对象。 -
获取时间, datetime
from datetime import datetime now = datetime.now() today = datetime.today()
-
a = "2020-01-03 20:50:39" b = datetime.strptime(a, '%Y-%m-%d %H:%M:%S')
-
filter
过滤函数:filter(过滤规则函数,待过滤数据)
li = [2,55,3,88] def func(x): return x>30 new = list(filter(func,li)) # [55,88]
-
enumerate()
: 返回一个可以枚举对象,得到索引和值li= [11,12,33] res = list(enumerate(li)) #[(0,11),(1,12),(2,33)]
-
匿名函数
lambda
: 用lambda表达式返回一个函数
👉一个匿名函数,实现的作用就是代替一些简单的函数,使得代码看上去更简洁并且可读性高。a = lambda x,y:x+y # a 是函数 print(a(11,22)) # 33
-
zip(list1,list2)
聚和打包
实践
1. 开头和输入
import sys
if __name__ == '__main__':
try: #异常捕获
aa = sys.stdin.readline().strip() #输入
a=aa.split(",")
except len(a)>1000000:
print("wrong")
else:
#中间略,a里面是int
b=bubble_sort(a)
quick_sort(a, 0, len(alist) - 1)
2. 冒泡排序:n^2
def bubble_sort(L):
for i in range(n-1):
for j in range(n-1-i):
if L[j] > L[j+1]:
L[j],L[j+1]=L[j+1],L[j]
return L
改进
def bubble_sort(L):
for i in range(len(nums) - 1):
ex_flag = False # 改进后的冒泡,设置一个交换标志位
for j in range(len(nums) - i - 1):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
ex_flag = True
if not ex_flag: #如果这一轮下了没有数字被交换,说明已经排好序,不用继续了
return nums
return nums # 这里代表计算机没有偷懒成功 o(╥﹏╥)o
3. 快速排序: nlogn
def quick_sort(array): #递归
if len(array)<=1:
return array
tmp = array[0]
left = [x for x in array[1:] if x<=tmp]
right = [x for x in array[1:] if x>tmp]
return quick_sort(left) + [tmp] + quick_sort(right)
- python 内置:sorted(),sort()
5. 99乘法表
for i in range(1, 10):
for j in range(1, i+1):
print('{}x{}={}\t'.format(j, i, i*j), end='')