[TOC]
python basic note
1. 基本运算
(1) + - * /
(2) 次方:x**y; 取模: x%y
2.类型
(1) type(x) : 查看变量类型
(2) float,int,bool(True,False),str
(3) list : [1,2,3] , [[1, "a"], [2, "b"], [3, "c"]]
数字索引: 正向索引,反向索引
a = [1, 2, 3] print(a[0], a[-1]) # output : 1 3
list 切割
a = [1,2,3,4,5,6] b = a[1:4] # [起点 : 终点 : 间隔] # 包含 不包含 print(b) # [2, 3, 4] print(a[:4]) # [1, 2, 3, 4] print(a[3:]) # [4, 5, 6] print(a[:]) # [1, 2, 3, 4, 5, 6] print(a[::2]) # [1, 3, 5] print(a[-4:-1]) # [3, 4, 5]
list 改变、增加、删除 元素
a = [1, 2, 3] b = [4, 5] c = a + b print(c) # [1, 2, 3, 4, 5] print(c + [6]) # [1, 2, 3, 4, 5, 6] del (c[0]) # 删除 或 a.pop(0) print(c) # [2, 3, 4, 5] c[0] = 0 # 改变 print(c) # [0, 3, 4, 5] a = [1, 2, 3] a.append(4) print(a) # [1, 2, 3, 4] a.insert(0, 9) print(a) # [9, 1, 2, 3, 4]
list拷贝
a = [1, 2, 3] aa = a aa[0] = 5 print(a) # [5, 2, 3] print(id(a), id(aa)) # 71881712 71881712 a = [1, 2, 3] aa = list(a) # 或 a[:] aa[0] = 5 print(a) # [1, 2, 3] print(id(a), id(aa)) # 74503352 73566288 # 浅拷贝 a = [[1, 2]] b = a[:] # 或 b = a 或 b = list(a) b[0][1] = 3 print(a) # [[1, 3]] # 深拷贝 import copy a = [[1, 2]] b = copy.deepcopy(a) b[0][1] = 3 print(a) # [[1, 2]]
(4) tuple 元组
a = (1, 2, 3) a = (1,) # 单元素tuple, 多加个逗号
(5) dict
d = { 1: "a", 2: "b", 3: "c" } for i in d: # 或 d.keys() print(d.get(i)) # 或 d[i] # a b c
作为 key 的元素必须不可变
(6) set
s = {1, 2, 3} # 或 s = set([1, 2, 3]) print(1 in set) # True
元素必须是不可变对象
3. 函数
# 可变参数 def avg(*args): return sum(args) / len(args) print(avg(1, 2, 3)) # 2.0 # 返回多个返回值 def get(x, y): return x, y x, y = get(1, 2) print(get(1, 2)) # (1, 2)
Python解释器会把传入的一组参数组装成一个tuple传递给可变参数
4.列表生成式
a = [1, 2, 3, 4, 5, 6] print([x*x for x in a if x % 3 == 2]) # [4, 25] print(["hello %s" % x for x in a if x % 2 == 0]) # ['hello 2', 'hello 4', 'hello 6'] print([x * y for x in a[2:4] for y in a[3:5]]) # [12, 15, 16, 20]
5.包
import xx
import xx as yy
from xx import yy