列表 list
a = ['apple', 'banana', 'cat']
a = [1, 2, 3]
# 下标
a[0] # apple
a[-2] # banana
# 末尾添加单个x元素
a.append([1, 2, 3]) # [1, 2, 3, [1, 2, 3]]
# 末尾添加多个元素
a.extend([1,2,3]) # [1, 2, 3, 1, 2, 3]
# 插入元素
a.insert(0, 'car')
# 删除元素
a.pop(0) # 删除并返回
del a[0]
a.remove(x) # 删除值为x的元素
# 查找元素x第一次出现的位置
a.index(x, start, stop) # 区间[start, stop)
# 判断x是否在a中
x in a
# 翻转
a.reverse()
# 长度 (python通用工具)
len(a)
# enumerate(a) = [(0, 'apple'),(1, 'banana'),(2, 'cat')]
for idx, x in enumerate(a):
print(idx, x)
# 强制转换list
b = list(range(5))
# 内置函数
max(a)
min(a)
sum(a)
#列表解析式
a = [x**2 for x in range(11) if x%2==0] # [0, 4, 16, 36, 64, 100]
# 切片
a[0:3:1] #[0, 3)
# 拷贝list
b = a[:]
b = a.copy()
字符串 str
# 转义字符
\t \n
\续航符
# 字符->unicode码
ord(x)
# unicode码->字符
chr(x)
# 字符串常用方法
isalnum() #是否全字母或数字
isalpha() #是否全字母或中文字符
isdigit() #是否全数字
islower() #是否全小写
isupper() #是否全大写
isspace() #是否全空白
istitle() #是否标题化
title() #标题化
lower() #变小写
upper() #变大写
swapcase() #大写转小写,小写转大写
lstrip() #截掉左边空格
rstrip() #截掉右边空格
strip() #截掉左右空格
repalce(old, new, 2) #将old替换成new,替换次数不超过2次
ljust(width,fillchar) #左对齐,fillchar填充
rjust(width,fillchar) #右对齐,fillchar填充
zfill(width) #右对齐,0填充
center(width,fillchar) #矩阵对齐
idx = a.find(str,beg=0,end=len(string)) #判断str是否在a中,如果指定查找范围则在[beg,end)中查找,返回找到的起始下标,不存在返回-1
# str->list
# split()
a, b = input().split() #输入123 456 -> a='123' b='456'
a = int(a) # a=123
b = int(b) # b=456
print(a+b) # 579
a, b = [int(x) for x in input().split()]
print(a+b)
# map() 输入
a = list(map(int, input().split()))
# list->str
# join() 输出
ss = ''.join(list) #list用''连接
# 格式化
print("{}: {}".format(x,y)
字典 dict
a = {'a'=1,'b'=2,'c'=3}
a = dict(a=1,b=2,c=3)
a = dict(['a',1],['b',2])
keys = ['a', 'b', 'c']
value = [1, 2, 3]
zipped = list(zip(keys,value))
print(zipped) # [('a',1),('b',2),('c',3)]
# 访问字典
a['a'] # 1
a.get('a', 'xxx') # 如果有'a'是key,则输出对应的a['a'], 如果没有输出xxx
# 修改元素
a['a'] = 6
# 删除
del a['a']
a.pop('a')
# 遍历
for x in a.keys()
for x in a.values()
for x in a.items() # 元组tuple形式
# 合并
s = {'a'=1,'b'=2,'c'=3}
t = {'a'=4,'b'=2,'d'=5}
s.update(t) # s = {'a'=4,'b'=2,'c'=3,'d'=5}
# 拷贝
a.copy()
集合 set
s = {1,2,3,4}
s = set() # 空集合
a = ['a','b']
s = set(a)
keys = ['a','b']
value = [1,2]
dic = dict(zip(keys,value))
s = set(dic.keys)
t = set(dic.items) # 二元组形式[(),()]
# 清空
s.clear()
# 添加
s.add()
s.update()
# 删除
s.pop()
s.remove() # 报错
s.discard() # 不报错
s&t # 交集
s|t # 并集
s-t # 差集
s^t # 对称差集
time
# 导入时间模块
import time
# 获取时间戳
start_time = time.time()
local_time = time.localtime() # 本地时间 time.struct_time(tm_year=2025, tm_mon=1, tm_mday=20, tm_hour=19, tm_min=22, tm_sec=52, tm_wday=0, tm_yday=20, tm_isdst=0)
print("年份",local_time.tm_year)
# 3s
time.sleep(3000)
# 格式化
t1 = time.strftime("%Y-%m-%d %H:%M:%S",start_time) # 把时间t按照format格式转换,返回字符串 2025-01-20 19:29:35
t2 = time.strptime("2025-1-20 11:21:59","%Y-%m-%d %H:%M:%S") # 把字符串按照format格式转换,返回时间 time.struct_time(tm_year=2025, tm_mon=1, tm_mday=20, tm_hour=11, tm_min=21, tm_sec=59, tm_wday=0, tm_yday=20, tm_isdst=-1)
#
datetime
import datetime
# 日期date
d = datetime.date(2023,10,1)
e = datetime.date(2024,2,5)
d.year
d.month
d.weekday() # 周几
# 时间 time
a = datetime.time(10,25,59)
b = datetime.time(4,20,58)
a.day
a.minute
# 日期时间 datetime
c = datetime.datetime(2023,10,1,10,25,58)
f = datetime.datetime.combine(d,a)
# 时间差 timedelta
delta = datetime.timedelta(days = 100, hours = 5)
c = c + delta
delta = f-c
# 格式化
out = c.strftime("%Y--%m--%d %H::%M::%S") # 时间日期转字符串
out = datetime.datetime.strptime("2023-10-1 10:25:50","%Y-%m-%d %H:%M:%S") #字符串转日期时间
函数
- 值传递:元组、字符串、数字
- 引用传递:列表、字典 (可以copy或切片来达到值传递的效果)
- 全局变量:global
导入模块
# 改名
import datetime as dt
from datetime import date, time, datetime
from datetime import * # 所有
内置函数
https://docs.python.org/zh-cn/3/library/functions.html
abs(x)
help(abs)
math
https://docs.python.org/zh-cn/3/library/math.html
# 常数
math.e
math.pi
math.ceil() # 向上取整
math.floor() # 向下取整
math.gcd() # 最大公约数
math.factorial() # 阶乘
collections
计数器:Counter (字典)
from collections import Counter
a = ['apple','banana']
b = Counter(a) # b = Counter({'apple': 1, 'banana': 1})
c = Counter() # Counter()
d = Counter('Hello World') # Counter({'l': 3, 'o': 2, 'H': 1, 'e': 1, ' ': 1, 'W': 1, 'r': 1, 'd': 1})
e = Counter([1,2,3,4,5]) # Counter({1: 1, 2: 1, 3: 1, 4: 1, 5: 1})
f = Counter({'a':1, 'b':2}) # Counter({'b': 2, 'a': 1})
g = Counter(a=1, b=2) # Counter({'b': 2, 'a': 1})
双端队列:deque (列表)
from collections import deque
a = deque([1,2,3,4])
a.append(5)
a.appendleft(0)
a.extend([6,7])
a.pop()
a.popleft()
a.remove(2)
a.rotate(1) # 列表向右移动
a.rotate(-1) # 列表向左移动
有默认值的字典:defaultdict
from collections import defaultdict
d = defaultdict(int)
d = defaultdict(list)
d = defaultdict(tuple)
d = defaultdict(dict)
d = defaultdict(set)
print(d['x']) # 0
print(a['x']) # []
print(e['x']) # ()
print(u['x']) # {}
print(i['x']) # set()
有序字典:OrderedDict
from collections import OrderedDict
dic = {('a',1),('b',2)}
d = OrderedDict(dic)
d.popiterm() # 删除最后一个元素
d.popiterm(Faulse) # 删除第一个元素
d.move_to_end('a') # 把a挪到尾部
d.move_to_end('b',False) # 把b挪到首部
堆 heapq
import heapq
heapq.heapify(a) # 将列表a转换成最小堆
heapq.heappush(a,x) # 添加x
heapq.heappop(a) # 删除最小元素
heapq.heapreplace(a,x) # 弹出并返回最小元素,添加x
while len(a):
print(heapq.heappop(a), end=" ") # 从小到大弹出
高阶函数 functools
偏函数 partial
from functools import partial
def Add(a, b, c):
print("a = ", a)
print("b = ", b)
print("c = ", c)
print("a + b + c = ", a + b + c)
Add_fix_c = partial(Add, c = 10)
Add_fix_c(1, 2)
迭代器 itertools
无限迭代器
from itertools import count, cycle, repeat
for x in count(start=0,step=1):
print(x)
if x>=1000:
break
for x in cycle("Hello"):
print(x)
for x in repeat(1):
print(x)
有限迭代器
from itertools import accumulate, chain
import operator
a = [1,2,3,4,5]
b = list(accumulate(a)) # 创建一个新的迭代器
print(b) # 前缀和:[1,3,6,10,15]
b = list(accumulate(a, operator.mul)) # [1, 2, 6, 24, 120]
c = list(chain('ABC','DEF')) # 合并多个迭代器
排列组合迭代器
from itertools import product, permutations, combinations
d = list(product([1,2,3], [4,5,6])) # 笛卡尔积 [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
e = list(permutations('1234')) # 排列
for x in e:
print(x)
('1', '2', '3', '4')
('1', '2', '4', '3')
('1', '3', '2', '4')
('1', '3', '4', '2')
('1', '4', '2', '3')
('1', '4', '3', '2')
('2', '1', '3', '4')
('2', '1', '4', '3')
('2', '3', '1', '4')
('2', '3', '4', '1')
('2', '4', '1', '3')
('2', '4', '3', '1')
('3', '1', '2', '4')
('3', '1', '4', '2')
('3', '2', '1', '4')
('3', '2', '4', '1')
('3', '4', '1', '2')
('3', '4', '2', '1')
('4', '1', '2', '3')
('4', '1', '3', '2')
('4', '2', '1', '3')
('4', '2', '3', '1')
('4', '3', '1', '2')
('4', '3', '2', '1')
f = list(combinations([1,2,3,4],3)) # 组合 选三个数
(1, 2, 3)
(1, 2, 4)
(1, 3, 4)
(2, 3, 4)
数组二分查找算法 bisect
from bisect import *
a = [1,2,2,2,3,4,5]
x = 2
print("x = {}, a中查找的第一个位置为:{}".format(x, bisect_left(a, x)))
print("x = {}, a中查找的第一个位置为:{}".format(x, bisect_right(a, x)))
insort_left(a, x)
print("a = ", a)
自定义排序
from functools import cmp_to_key
a = [1,3,5,-2,4,9,7]
sorted_a = sorted(a) # 从小到大 不改变原list 有返回值
sorted_b = sorted(a, reverse=True) # 从大到小
# 自定义规则:当a<b返回负数,当a>b返回正数,相等返回0
def cmp(a, b):
if abs(a) < abs(b):
return -1
elif abs(a) < abs(b):
return 1
else:
return 0
sorted_c = sorted(a, key=cmp_to_key(cmp)) # 绝对值从小到大
def cmp2(a, b):
if sum(a) < sum(b):
return -1
elif sum(a) > sum(b):
return 1
else:
if a[0] < b[0]:
return -1
elif a[0] > b[0]:
return 1
else:
return 0
b = [(6,3),(-1,10),(6,2),(5,4),(5,8)]
sorted_d = sorted(b, key=cmp_to_key(cmp2)) # 二元组和从小到大排序,和相同看第一个元素从小到大
a = [1,5,3,2,4]
a.sort() # 无返回值 改变原list
类与对象
https://pyzh.readthedocs.io/en/latest/
class stu:
# 类的属性
sex_list=['boy','girl']
# 类的方法
@classmethod
def get_sex(cls):
return cls.sex_list
# 构造函数
def __init__(self, name, sex, class_idx):
# 实例属性
self.name=name
self.sex=sex
self.class_idx=class_idx
# 实例方法
def get_sex(self):
return self.sex_list[self.sex]
stu1 = stu("Alice", 1, 5)
print(stu.sex_list)
print(stu1.name)
print(stu1.sex)
print(stu1.class_idx)
print(.get_sex())