跳转至

Python

基础语法

sorted

sorted(xxx)返回的是list,不能放进set,可以tuple(sorted(xxx)),因为tuple是hashable

a = [1, 2, 3]
b = set()
b.add(a) # exception
b.add(tuple(a))

range

  • range(1, 3): [1, 2]
  • range(3, 1, -1): [3, 2]

参数

函数传参传的是对象引用的副本,理解成形参是另一个变量,只是指向同一个对象 - 如果是可变类型,直接修改,例如list.append,那么外面对象会受影响 - 如果是原生类型,Python中看作不可变类型,执行x += 1其实是创建一个新的int副本,然后把形参指过去,所以外面的值不受影响 - 如果执行x = ...,外面的值不受影响

from typing import List

x = 1
def f(x: int) -> None:
    x += 1
f(x)
print(x) # 1

x = [1, 2]
def f(x: List[int]) -> None:
    x.append(3)
f(x)
print(x) # [1, 2, 3]

any

一个list中有任何一个为True

print(any([n == 9 for n in range(5)])) # False
print(any([n == 9 for n in range(20)])) # True

注解

  • Optional[XXX]: 可能为None
  • Tuple[int, int]
  • Tuple[int, ...]
fn: Callable[[], None]
fn()

tuple

定义方式可以加上括号,可以不加括号,如果只有一个元素,必须后面加上逗号

t = ()
print(type(t))  # <class 'tuple'>
t = (1,)
print(len(t))   # 1
print(type(t))  # <class 'tuple'>
t = 1, "2"
print(len(t))   # 2
print(type(t))  # <class 'tuple'>

from typing import Tuple
def f() -> Tuple[int,int]:
    return 1, 2, 3
t = f()
print(len(t))   # 3
print(type(t))  # <class 'tuple'>

list

a = list()
a.append(1) # [1]
a.extend([2, 3, 4]) # [1, 2, 3, 4]
a.pop() # [1, 2, 3]

zip语法:两个列表交叉

a = [1, 2, 3]
b = ["A", "B", "C"]
print(list(zip(a, b))) # [(1, "A"), (2, "B"), (3, "C")]

for x, y in zip(a, b):
    print(x, y)

长度不一样时,zip 会以最短的为准:

queue

from collections import deque

  q = deque()

  q.append(1)      # enqueue
  q.append(2)
  q.append(3)

  x = q.popleft()  # dequeue, x = 1

  print(q)         # deque([2, 3])

  常用 API

  q.append(x)      # 右边入队
  q.popleft()      # 左边出队
  q.pop()           # 右边出队
  q[0]             # 看队头
  len(q)           # 队列长度
  if q:            # 判断非空

Map

  • keys()
  • values()
  • items()

dict

defaultdict: 访问不存在的key时自动初始化

from collections import defaultdict

d = defaultdict(set)
d[1].add(1) # {1: {1}}

Set

要显式定义

a = set()
a.add(1)

排列组合

combination: 不重复

permutation: 考虑顺序

from itertools import combinations, permutations

items = ["A", "B", "C"]

"""
('A', 'B')
('A', 'C')
('B', 'C')
"""
for pair in combinations(items, 2):
    print(pair)

"""
A B
A C
B C
"""
for i, j in combinations(items, 2):
    print(i, j)

"""
A B
A C
B A
B C
C A
C B
"""
for i, j in permutations(items, 2):
    print(i, j)

set