Python变量
可以使用del删除已经定义的变量
1
| del value_name, value_name_2
|
Python数据类型
- 数字 Numbers
- 整型 int
- 浮点型 float
- 布尔型 bool
- 复数型 complex
- 字符串 String
- 列表 List
- 元组 Tuple
- 集合 Sets
- 字典 Dictionaries
python3中有以下几种seq类型的变量
seq数据类型提供了以下内置函数:
- len
- max
- min
- list
- str
- sum
- sorted
- reversed
- enumerate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| print(type(1)) print(type(1.1)) print(type(True)) print(type(3+4j))
print(type('1213'))
print(type([1, 2, 3]))
print(type((1,2,3)))
print(type({1, 2, 3}))
print(type({1: 2, 3: 4}))
|
1
| print(isinstance(1, int))
|
isinstance 和 type 的区别在判定子类与其继承的父类的关系时会体现出来:
1 2 3 4
| class Parent: pass class Children(Parent): pass
|
type
1 2
| print(type(Children()) == Children) print(type(Children()) == Parent)
|
isinstance
1
| print(isinstance(Children(), Parent))
|
Number
- int(x)
- float(x)
- complex(x)
- complex(x, y)
String
在字符串前加r前缀,能够使转义字符无效化
1 2
| print("abc\tdef") print(r"abc\ndef")
|
使用 “””…””” 或 ‘’’…’’’ 表示续行
1 2 3 4 5 6 7 8 9 10
| print(''' <div> <p>Hello World</p> </div> ''') print(""" <div> <p>Hello World</p> </div> """)
|
1 2 3
| string = '123456789' print(string[0]) print(string[-1])
|
1
| string[[start_index] : [end_index]]
|
1 2 3 4 5 6
| string = '123456789' print(string[1:5]) print(string[:]) print(string[:5]) print(string[5:]) print(string[-5:-1])
|
1 2 3
| str = "Hello World" print("ll" in str) print('m' in str)
|
和C/C++的printf方法类似
1 2
| print("It's %d o'clock, let's %s" % (18, "go off work"))
|
与JavaScript的模板字符串类似
1 2 3
| time, event = 18, 'get off work'
print(f"it's {time} o'clock, let's {event}")
|
List
列表加法
1 2 3
| list_A = [1,2,3,4,5] list_B = [2,3,4,5,6] print(list_A+list_B)
|
列表乘法
1 2
| list_A = [1,2,3] print(list_A*2)
|
乘法也能用于初始化指定长度的列表:
List可以通过切片进行增删改查操作
1 2 3
| arr = list('123456789') arr[0:0] = ['m', 'n'] print(arr)
|
1 2 3
| arr = list('123456789') arr[2:3] = [] print(arr)
|
1 2 3
| arr = list('123456789') arr[0:2] = ['m', 'n'] print(arr)
|
1 2
| arr = list('123456789') print(arr[2:3])
|
1 2 3 4 5 6 7
| list_A = [] list_A.append(1) print(list_A) list_A.insert(0, 2) print(list_A) list_A.extend([3,4]) print(list_A)
|
1 2 3 4 5 6 7
| list_A = [1,2,3,4,3,5] list_A.pop() print(list_A) list_A.remove(3) print(list_A) list_A.clear() print(list_A)
|
1 2 3
| list_A = [1,2,3,4,3,5] print(list_A.count(3)) print(list_A.index(3))
|
1 2 3 4 5 6 7
| from collections import deque queue = deque([1, 2, 3]) queue.append(4) queue.append(5) print(queue.popleft()) print(queue.popleft()) print(queue)
|
[expression(x) for x in seq]
1 2 3 4 5
| vec = [2, 4, 6] str_arr = ['key1:value1', 'key2:value2', 'key3:value3'] print([3*x for x in vec]) print([[x,x**2,x**3] for x in vec]) print(dict(str.split(':') for str in str_arr))
|
加入if过滤
[expression(x) for x in seq if expression(x)]
1 2 3 4
| vec = [2, 4, 6] str_arr = ['key1:value1', 'key2:value2', 'key3:value3'] print([3*x for x in vec if x != 4]) print(dict(str.split(':') for str in str_arr if '1' not in str))
|
嵌套循环
[expression(n_1, n_2, …) for n_1 in arr_1 for n_2 in arr_2 …]
1 2 3
| vec1 = [1,-1,2,-2,3,-3] vec2 = [3,-3,4,-4,5,-5] print([x*y for x in vec1 if x>0 for y in vec2 if y <0])
|
1 2 3 4 5 6 7
| matrix_m_n = [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ] matrix_n_m = [[row[i] for row in matrix_m_n] for i in range(len(matrix_m_n[0]))] print(matrix_n_m)
|
del list[start:end]
1 2 3
| arr = [1,2,3,4,5] del arr[1:2] print(arr)
|
Tuple
元组元素无法修改,
当元组中只有一个元素时,需要在唯一元素后加一个逗号,否则会被当做括号运算符
1 2 3 4 5 6
| tup1 = () tup2 = (2,) tup3 = (2) print(tup1) print(tup2) print(tup3)
|
甚至可以不加括号的创建元祖:
1 2
| t = 123, 'hello', True, ('abc', False) print(t)
|
Tuple支持加法拼接:
1 2 3
| tup_1 = (1,) tup_2 = (2,) print(tup_1 + tup_2)
|
operator是专门用来实现数据比较功能的模块
1 2 3 4 5 6
| import operator tup_1 = (1, 2) tup_2 = (2, 1) tup_3 = (2, 1) print(operator.eq(tup_1, tup_2)) print(operator.eq(tup_2, tup_3))
|
Sets
创建空集合需要使用set,方便和空字典区分开:
1 2
| blank_set = set() blank_dict = {}
|
1 2 3 4 5 6 7 8 9 10
| set_A = {1, 2, 3, 4, 5, 4, 3, 2, 1} set_B = {4, 5, 6, 7, 8, 6, 5, 4}
print(set_A - set_B)
print(set_A | set_B)
print(set_A & set_B)
print(set_A ^ set_B)
|
- discard 移除不存在的集合元素时不会报错
- remove 移除不存在的集合元素时会报错
- clear 清除所有
- difference_update 移除差集
- intersection_update 保留交集
- symmetric_difference_update 保留异或集
- pop 随机删除
- discard 删除指定
- remove 删除指定
- difference 差集
- intersection 交集
- symmetric_difference 异或集
- union 并集
- isdisjoint 是否存在交集
- issubset 判断子集
Dictionaries
dict的key只能是不可改变类型的数据
1 2 3 4
| dict_A = { 1: 123, "a": 321 }
|
1 2
| dict_A = dict(a=1, b=2, c=3) print(dict_A)
|
1 2 3 4 5 6
| tup = ( ('a', 1), ('b', 2), ('c', 3) ) print(dict(tup))
|
1 2 3 4 5 6
| dict_list = [ ['a', 1], ['b', 2], ['c', 3] ] print(dict(dict_list))
|
1 2 3 4 5 6
| set_dict = [ {'a', 1}, {'b', 2}, {'c', 3} ] print(dict(set_dict))
|
set是无序集合,因此创建出来的字典键值关系随机组合
1 2
| for_dict = {x: y**2 for x, y in [['a', 1], ['b', 2], ['c', 3]]} print(for_dict)
|
1 2 3 4 5 6 7 8
| dict_list = [ ['a', 1], ['b', 2], ['c', 3] ] new_dict = dict(dict_list) print('a' in new_dict) print(1 in new_dict)
|
1
| dict.fromkeys(seq[, value])
|
1 2
| new_dict = dict.fromkeys(["a", "b", "c"], 123) print(new_dict)
|
1
| dict.get(key[, default=None])
|
1 2 3
| new_dict = {"a": 1, "b": 2, "c": 3} print(new_dict.get("a", 123)) print(new_dict.get("e", 123))
|
1
| dict.setdefault(key[, default=None])
|
1 2 3 4
| new_dict = {"a": 1, "b": 2, "c": 3} print(new_dict.setdefault("a", 123)) print(new_dict.setdefault("e", 123)) print(new_dict)
|
1
| target_dict.update(source_dict)
|
1 2 3 4
| dict_A = {"a": 1, "b": 2, "c": 3} dict_B = {"a":111, "e":123} dict_A.update(dict_B) print(dict_A)
|
运算符
对于一些简单通用运算符,python和其他语言的差别不大:
- 算术运算符
- 比较运算符
- 赋值运算符
- 位运算符
- 逻辑运算符
- 成员运算符
- 身份运算符
1 2 3 4 5 6 7 8
| new_list = [x for x in [1, 2, 3]] new_set = {x for x in [1, 2, 3]} new_tuple = (1, 2, 3) new_dict = {x: x + 1 for x in [1, 2, 3]} print(1 in new_list) print(1 in new_set) print(1 in new_tuple) print(1 in new_dict)
|
1
| (A is B) = (id(A) == id(B))
|
循环
for-in
利用range控制循环次数
1 2 3
| num_list = list('0123456789') for i in range(0, len(num_list), 3): print(i)
|
利用range创建数字序列
1 2 3
| print(list(range(0, 10, 3))) print(tuple(range(0, 10, 3))) print(set(range(0, 10, 3)))
|
for-in/while + else
进入else的条件:
1 2 3 4 5 6 7
| for n in range(2,10): for m in range(2,n): if n%m == 0: print(n, 'equals', m, '*', n//m) break else: print(n, 'is a prime number')
|
进入else的条件:
- while条件为False
- 循环没有被break终止
1 2 3 4 5 6 7 8 9 10 11
| n = 2 while n<10: m = 2 while m<n: if n%m == 0: print(f"{n} = {m} * {n//m}") break m+=1 else: print(f'{n} is prime number') n+=1
|
迭代器&&生成器
可用于创建迭代器的数据类型:
迭代器的两个主要函数:
- iter() 创建迭代器
- next(iter) 访问下一个元素
1 2 3 4 5 6
| it_list = iter(list('123')) while True: try: print(next(it_list)) except: break
|
使用了yield的函数被称为generator函数,
每次运行到yield语句时,都将返回yield后的值,
在执行next()时触发生成器的执行
1 2 3 4 5 6 7 8 9 10 11
| def fibonacci(n): a, b, counter = 0, 1, 0 while counter <= n: counter += 1 yield a a, b = b, a + b return
it = fibonacci(10) print(list(it))
|
函数
1 2 3 4 5 6 7
| def printinfo(name, age=35): print(name, age) return
printinfo(age=20, name='a')
|
1 2 3 4 5 6 7
| def printinfo(name, age=35): print(name, age) return
printinfo(name='a') printinfo(name='b' , age=20)
|
- def fun(*args)
- def fun(**args)
推荐写法: 可变参数放最后
1 2 3 4 5 6
| def printinfo(arg1, *args): print(arg1, args)
printinfo("abc", 1, 2, 3) printinfo("abc")
|
可变参数写在前, 固定参数需使用关键字参数传入
1 2 3 4 5 6 7
| def printinfo(*args, arg1=123): print(args, arg1)
printinfo(1, 2, 3, arg1=1) printinfo(arg1=1) printinfo(1, 2, 3)
|
1 2 3 4 5
| def printinfo(**args): print(args)
printinfo(a = 1, b = 2, c = 3)
|
- lambda 只是一个表达式
- lambda 无法访问自有参数以外的任何参数
1
| lambda [args, [args2,....argn]]: expression
|
1 2 3
| arr_add1 = lambda arg: int(arg)+1 arr = list('123') print(list(map(arr_add1, arr)))
|