String
str.isalpha()
:判断字符串是否只由字母组成str.endswith(word)
:判断字符串末尾是否是wordstr.upper()
:把所有小写转换成大写str.lower()
:把所有大写转换成小写str.capitalize()
:把第一个字母转化为大写字母,其余小写str.title()
:把每个单词的第一个字母转化为大写,其余小写
list
l = [[0 for i in range(n)] for j in range(n)]
l = [[0]*n]*n
- 倒叙:
list.reverse()
/ list[::-1]
- 排序:
list.sort()
- 利用collections.deque([])降低时间复杂度
a = collections.deque([])
a.popleft()
a.pop()
a.appendleft(x)
a.extend([x,y])
dict
d = {1:3, 2:2, 3:1}
sorted(d.keys(), reverse=True)
sorted(tryd.items(), key=lambda item:item[1])
a = {}
a = collections.defaultdict(list)
a.update(b)
set
set.add(item)
set.remove(item)
random.choice(tuple(set))
heap
heapq.heappop(heap)
heapq.heappush(heap, item)
heapq.heapify([])
heapq._heapify_max(data)
heap.heapreplace(data, new_item)
其他常用
for i in range(n-1, -1, -1)
- 无穷
∞
\infty
∞:float(“inf”)
isinstance(l, list)
:判断是否是listall((a,b,c))
:如果a,b,c都是True则返回Truerandom.randint(a, b)
:随机返回[a,b]间的整数
注意事项
- 全局变量
- 可变对象:list dict set
- 不可变对象:tuple string int float bool
- 可变对象在函数中可直接当全局变量使用
- 不可变对象在函数中需要声明"global var",且不可用于递归recursive中
- 查询效率:set > dict >> list
其他知识点
- ^异或 1<<5,相当于把第5位从0变到1,从1变到0, 即实现大小写的转换
- 0 ^ 0=0 , 0 ^ 1= 1 , 1 ^ 0= 1 , 1 ^ 1= 0
ord()
返回对应的ASCII码chr()
返回对应的ASCII字符itertools.product(a,b)
: 笛卡尔积
return ["".join(s) for s in itertools.product(*L)]
bisect(list, target)
,二分查找,返回high,即若找到则坐标为high-1,若没找到则前一位是high-1,应插入high位- 负数除以整数取余:比如-1%5=4(-1/5=(-1)余4),-7/3=-3余2