更新于 

Python基础语法

Python变量

变量定义与赋值

同时对多个变量赋值

1
2
3
# a = 1
# b = 2
a, b = 1, 2
变量删除

可以使用del删除已经定义的变量

1
del value_name, value_name_2

Python数据类型

  • 数字 Numbers
    • 整型 int
    • 浮点型 float
    • 布尔型 bool
    • 复数型 complex
  • 字符串 String
  • 列表 List
  • 元组 Tuple
  • 集合 Sets
  • 字典 Dictionaries
序列sequence的内置函数

python3中有以下几种seq类型的变量

  • list
  • tuple
  • set
  • dict

seq数据类型提供了以下内置函数:

  • len
  • max
  • min
  • list
  • str
  • sum
  • sorted
  • reversed
  • enumerate
变量检测函数 type
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
### Numbers
print(type(1)) # <class 'int'>
print(type(1.1)) # <class 'float'>
print(type(True)) # <class 'bool'>
print(type(3+4j)) # <class 'complex'>
### String
print(type('1213')) # <class 'str'>
### List
print(type([1, 2, 3])) # <class 'list'>
### Tuple
print(type((1,2,3))) # <class 'tuple'>
### Sets
print(type({1, 2, 3})) # <class 'set'>
### Dictionaries
print(type({1: 2, 3: 4})) # <class 'dict'>
类检测 isinstance
1
print(isinstance(1, int)) # True

isinstancetype 的区别在判定子类与其继承的父类的关系时会体现出来:

1
2
3
4
class Parent:
pass
class Children(Parent):
pass

type

1
2
print(type(Children()) == Children)     # True
print(type(Children()) == Parent) # False

isinstance

1
print(isinstance(Children(), Parent))   # True

Number

python的除法

python中存在两种除法:

1
2
print(5/2)   # 2.5
print(5//2) # 2
  • a/b
    • 除法,返回float类型数值
  • a//b
    • 整除,返回int类型数值
数字类型转换
  • int(x)
  • float(x)
  • complex(x)
  • complex(x, y)
    • x: 实数部分
    • y: 虚数部分

String

前缀

在字符串前加r前缀,能够使转义字符无效化

1
2
print("abc\tdef")   # abc	def
print(r"abc\ndef") # 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>
""")
索引
  • 正向索引
    • 从左向右
    • 从0开始递增
  • 负向索引
    • 从右向左
    • 从-1开始递减
      1
      2
      3
      string = '123456789'
      print(string[0]) # 1
      print(string[-1]) # 9
切片
1
string[[start_index] : [end_index]]
1
2
3
4
5
6
string = '123456789'
print(string[1:5]) # 2345
print(string[:]) # 123456789
print(string[:5]) # 12345
print(string[5:]) # 6789
print(string[-5:-1]) # 5678

字符串不能通过索引值引用的方式改变

子串
1
2
3
str = "Hello  World"
print("ll" in str) # True
print('m' in str) # False
格式化
字符串格式化

和C/C++的printf方法类似

1
2
# It's 18 o'clock, let's go off work
print("It's %d o'clock, let's %s" % (18, "go off work"))
f-string

与JavaScript的模板字符串类似

1
2
3
time, event = 18, 'get off work'
# it's 18 o'clock, let's 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, 3, 4, 5, 2, 3, 4, 5, 6]

列表乘法

1
2
list_A = [1,2,3]
print(list_A*2) # [1, 2, 3, 1, 2, 3]

乘法也能用于初始化指定长度的列表:

1
print([None]*5)  # [None, None, None, None, None]
切片

List可以通过切片进行增删改查操作

1
2
3
arr = list('123456789')
arr[0:0] = ['m', 'n']
print(arr) # ['m', 'n', '1', '2', '3', '4', '5', '6', '7', '8', '9']
1
2
3
arr = list('123456789')
arr[2:3] = []
print(arr) # ['1', '2', '4', '5', '6', '7', '8', '9']
1
2
3
arr = list('123456789')
arr[0:2] = ['m', 'n']
print(arr) # ['m', 'n', '22', '3', '4', '5', '6', '7', '8', '9']
1
2
arr = list('123456789')
print(arr[2:3]) # ['3']
List内建函数
  • append
  • extend
  • insert
1
2
3
4
5
6
7
list_A = []
list_A.append(1)
print(list_A) # [1]
list_A.insert(0, 2)
print(list_A) # [2, 1]
list_A.extend([3,4])
print(list_A) # [2, 1, 3, 4]
  • pop
  • remove
  • clear
1
2
3
4
5
6
7
list_A = [1,2,3,4,3,5]
list_A.pop()
print(list_A) # [1,2,3,4,3]
list_A.remove(3)
print(list_A) # [1,2,4,3]
list_A.clear()
print(list_A) #[]
  • count
  • index
1
2
3
list_A = [1,2,3,4,3,5]
print(list_A.count(3)) # 2
print(list_A.index(3)) # 2
  • append 入栈
  • pop 出栈
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()) # 1
print(queue.popleft()) # 2
print(queue) # deque([3, 4, 5])
列表推导式

[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]) # [6, 12, 18]
print([[x,x**2,x**3] for x in vec]) # [[2, 4, 8], [4, 16, 64], [6, 36, 216]]
print(dict(str.split(':') for str in str_arr)) # {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

加入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]) # [6, 18]
print(dict(str.split(':') for str in str_arr if '1' not in str)) # {'key2': 'value2', 'key3': 'value3'}

嵌套循环
[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) # [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
切片删除

del list[start:end]

1
2
3
arr = [1,2,3,4,5]
del arr[1:2]
print(arr) # [1, 3, 4, 5]
zip 根据索引同时访问多个序列

Tuple

创建规则

元组元素无法修改,
当元组中只有一个元素时,需要在唯一元素后加一个逗号,否则会被当做括号运算符

1
2
3
4
5
6
tup1 = ()
tup2 = (2,)
tup3 = (2)
print(tup1) # ()
print(tup2) # (2,)
print(tup3) # 2

甚至可以不加括号的创建元祖:

1
2
t = 123, 'hello', True, ('abc', False)
print(t) # (123, 'hello', True, ('abc', False))

Tuple支持加法拼接:

1
2
3
tup_1 = (1,)
tup_2 = (2,)
print(tup_1 + tup_2) # (1, 2)
元组的比较:operator

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)) # False
print(operator.eq(tup_2, tup_3)) # True

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) # {1, 2, 3}
# 并集
print(set_A | set_B) # {1, 2, 3, 4, 5, 6, 7, 8}
# 交集
print(set_A & set_B) # {4, 5}
# 异或
print(set_A ^ set_B) # {1, 2, 3, 6, 7, 8}
Set内置方法
  • add 添加单个
  • update 保留并集/添加元素
discard和remove的区别
  • discard 移除不存在的集合元素时不会报错
  • remove 移除不存在的集合元素时会报错
  • clear 清除所有
  • difference_update 移除差集
  • intersection_update 保留交集
  • symmetric_difference_update 保留异或集
  • pop 随机删除
  • discard 删除指定
  • remove 删除指定
  • difference 差集
  • intersection 交集
  • symmetric_difference 异或集
  • union 并集
  • isdisjoint 是否存在交集
  • issubset 判断子集

Dictionaries

构建字典

dict的key只能是不可改变类型的数据

  • number
  • string
1
2
3
4
dict_A = {
1: 123,
"a": 321
}
1
2
dict_A = dict(a=1, b=2, c=3)
print(dict_A) # {'a': 1, 'b': 2, 'c': 3}
1
2
3
4
5
6
tup = (
('a', 1),
('b', 2),
('c', 3)
)
print(dict(tup)) # {'a': 1, 'b': 2, 'c': 3}
1
2
3
4
5
6
dict_list = [
['a', 1],
['b', 2],
['c', 3]
]
print(dict(dict_list)) # {'a': 1, 'b': 2, 'c': 3}
1
2
3
4
5
6
set_dict = [
{'a', 1},
{'b', 2},
{'c', 3}
]
print(dict(set_dict)) # {'a': 1, 'b': 2, 3: 'c'}

set是无序集合,因此创建出来的字典键值关系随机组合

1
2
for_dict = {x: y**2 for x, y in [['a', 1], ['b', 2], ['c', 3]]}
print(for_dict) # {'a': 1, 'b': 4, 'c': 9}
成员测试
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) # True
print(1 in new_dict) # False
Dict 内置方法
快速创建新字典
1
dict.fromkeys(seq[, value])
1
2
new_dict = dict.fromkeys(["a", "b", "c"], 123)
print(new_dict) # {'a': 123, 'b': 123, 'c': 123}
获取指定键值
1
dict.get(key[, default=None])
1
2
3
new_dict = {"a": 1, "b": 2, "c": 3}
print(new_dict.get("a", 123)) # 1
print(new_dict.get("e", 123)) # 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)) # 1
print(new_dict.setdefault("e", 123)) # 123
print(new_dict) # {'a': 1, 'b': 2, 'c': 3, 'e': 123}
字典更新
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) # {'a': 111, 'b': 2, 'c': 3, 'e': 123}

运算符

对于一些简单通用运算符,python和其他语言的差别不大:

  • 算术运算符
  • 比较运算符
  • 赋值运算符
  • 位运算符
  • 逻辑运算符
    • and
    • or
    • not
  • 成员运算符
    • in
    • not in
  • 身份运算符
    • is
    • is not
成员运算符
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) # True
print(1 in new_set) # True
print(1 in new_tuple) # True
print(1 in new_dict) # True
身份运算符
1
(A is B) = (id(A) == id(B))

循环

for-in

range()函数
1
range(start, end, step)

利用range控制循环次数

1
2
3
num_list = list('0123456789')
for i in range(0, len(num_list), 3):
print(i) # 0 3 6 9

利用range创建数字序列

1
2
3
print(list(range(0, 10, 3)))  # [0, 3, 6, 9]
print(tuple(range(0, 10, 3))) # (0, 3, 6, 9)
print(set(range(0, 10, 3))) # {0, 9, 3, 6}

for-in/while + else

for-in-else

进入else的条件:

  • 穷尽列表
  • 循环没有被break终止
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')
while-else

进入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

可用于创建迭代器的数据类型:

  • String
  • List
  • Tuple
  • Set
  • Dict

迭代器的两个主要函数:

  • iter() 创建迭代器
  • next(iter) 访问下一个元素
1
2
3
4
5
6
it_list = iter(list('123'))
while True:
try:
print(next(it_list))
except:
break
生成器 generator

使用了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)) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

函数

关键字参数
1
2
3
4
5
6
7
def printinfo(name, age=35):
print(name, age)
return


printinfo(age=20, name='a') # a 20

缺省参数
1
2
3
4
5
6
7
def printinfo(name, age=35):
print(name, age)
return


printinfo(name='a') # a 35
printinfo(name='b' , age=20) # b 20
可变参数
  • def fun(*args)
    • args以Tuple类型传入
  • def fun(**args)
    • args以Dict类型传入
可变Tuple参数 *arg

推荐写法: 可变参数放最后

1
2
3
4
5
6
def printinfo(arg1, *args):
print(arg1, args)


printinfo("abc", 1, 2, 3) # abc (1, 2, 3)
printinfo("abc") # abc ()

可变参数写在前, 固定参数需使用关键字参数传入

1
2
3
4
5
6
7
def printinfo(*args, arg1=123):
print(args, arg1)


printinfo(1, 2, 3, arg1=1) # (1, 2, 3) 1
printinfo(arg1=1) # () 1
printinfo(1, 2, 3) # (1, 2, 3) 123
可变Dict参数 **args
1
2
3
4
5
def printinfo(**args):
print(args)

# {'a': 1, 'b': 2, 'c': 3}
printinfo(a = 1, b = 2, c = 3)
匿名函数 lambda
  • 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))) # [2, 3, 4]