阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。
1. self关键字
仅在两种情况下使用:
- class的method/attribute定义
PYTHON · 仅供阅读 self.val = 1 def method(self, nums, target): # do sth - class内部使用
PYTHON · 仅供阅读 self.val self.method(nums, target)
常见self错误:
- class外部绝不会出现self
- 另一个错误:缺少self
整理注: self是普通参数名的惯例,不是关键字;可在类外命名变量self。这里讨论的是实例方法的常规写法,staticmethod/classmethod另有规则。
class Solution():
def find(nums, target): # 缺少self
pass
s = Solution() # 必须要有()
s.find([0, 1, 2, 3, 4], 1)TypeError: find() takes 2 positional arguments but 3 were given
2.元素序列
2.1 list: size可变,值可变(mutable)
2.1.1 删除元素
list1 = [1, 4, 2, 3, 1, 10]
list1.remove(1) # 删除第一个1
print(list1)[4, 2, 3, 1, 10]
list1.pop(0) # delete by index
print(list1)
list1.pop() # 删除最后一个
print(list1)[2, 3, 1, 10]
[2, 3, 1]
del list1[0] # delete by index
print(list1)[3, 1]
2.2 tuple: size不可变,值不可变(immutable)
t = (1,2)整理注: tuple不可变是指其元素引用不能替换,内部若持有可变对象,该对象仍可改变。
2.3 dict: Python 3.7 起保证插入顺序(不是按键排序)
2.3.1 Create a dict
d = {'Jack':1557, 'Tom':1320, 'Rose':10}
print(d['Jack'])1557
d = dict([('Jack', 1557), ('Tom', 1320), ('Rose', 10)])
print(d){'Jack': 1557, 'Tom': 1320, 'Rose': 10}
2.3.2 items(), keys(), values()
print(d.items())
for k, v in d.items():
print(k, v)dict_items([('Jack', 1557), ('Tom', 1320), ('Rose', 10)])
Jack 1557
Tom 1320
Rose 10
print(d.keys())
print(d.values())dict_keys(['Jack', 'Tom', 'Rose'])
dict_values([1557, 1320, 10])
2.3.3 pop()
dict.pop(key[,default])- key: 要删除的key
- default: 如果没有 key,返回 default 值
- 返回被删除的value
print(d.pop('Jack'))
print(d)1557
{'Tom': 1320, 'Rose': 10}
print(d.pop('Morse'))KeyError: 'Morse'
print(d.pop('Morse', 'No such key'))No such key
2.4 set: 不保证顺序的不重复元素序列
2.4.1 Create a set
s = set([1, 1, 2, 3]) # 去重
print(s){1, 2, 3}
s = {'b', 'a', 'c'}
print(s){'a', 'b', 'c'}
用于创建set须为可迭代对象,且元素可哈希
s = set(1, 2, 3) # 错误写法TypeError: set expected at most 1 argument, got 3
s = set([1, 2, 3]) # 正确写法
print(s){1, 2, 3}
s = set('abc')
print(s)
# 注意区别:
s = set(['abc'])
print(s){'c', 'b', 'a'}
{'abc'}
2.4.2 add()
s = set('abc') # 不保证顺序
s.add(1)
print(s){'c', 'b', 1, 'a'}
2.4.3 移除元素
s.remove(x)- 将元素 x 从集合 s 中移除,如果元素不存在,则会发生错误
s.remove(1)
print(s){'c', 'b', 'a'}
s.remove(1)KeyError: 1
s.discard(x)- 移除集合中的元素,且如果元素不存在,不会发生错误
s.discard(1)3. 看懂doc
3.1 min()
min(arg1, arg2, *arg[, key])- *arg: 可输入不确定个数参数
print(min(1, 2))
print(min(1, 2, 3))
print(min(1, 2, 3, 4))1
1
1
3.1 print()
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)print(1, 2, 3, 4, sep="-", end="=")
print(1, 2, 3, 4, sep="-")1-2-3-4=1-2-3-4