1、按關(guān)鍵字排序
a.第一關(guān)鍵字升序
intervals = sorted(intervals, key=lambda x:x[0])
b.多關(guān)鍵字,第一關(guān)鍵字降序
people = sorted(people, key = lambda x:(-x[0], x[1]))
c.自定義比較函數(shù)
def compare(x, y):
? ? ? ? ? ? #小于0的時(shí)候調(diào)換位置
? ? ? ? ? ? return int(y+x) - int(x+y)
nums = sorted(map(str, nums), key=cmp_to_key(compare))
2、累積函數(shù)
reduce函數(shù):每次從list中取一個(gè)元素和上一次的結(jié)果做運(yùn)算?
reduce(lambda x, y: x ^ y, nums)
3、ascii碼和字符的互換
a.
ord(‘a(chǎn)’)
b.
chr(97)
4、小頂堆的使用
import heapq
h=[]
heapq.heapify(h)
heapq.heappush(h,2)
heapq.heappop(h)
5、記憶化搜索
import functools
@functools.lru_cache(None)
6、獲取數(shù)字的二進(jìn)制表示
bin(8)
負(fù)數(shù)的時(shí)候需要考慮補(bǔ)碼
bin(-8 & & 0b1111111111111111)
7、計(jì)算字符串中某個(gè)字符的數(shù)量
s.count(ss)
8、計(jì)算不同值出現(xiàn)的個(gè)數(shù)
import collections
dic = collections.Counter(tasks)
9、map函數(shù)用法
map() 函數(shù)語法:map(function, iterable, …)
a.?
def square(x) : # 計(jì)算平方數(shù)
?????return x ** 2
A=list(map(square, [1,2,3,4,5])) # 計(jì)算列表各個(gè)元素的平方
b.
list(map(lambda x: x * x, data))
10、filter函數(shù)用法
filter(function, iterable) #function為判斷函數(shù),iterable為可迭代對象
以下代碼展示了從列表中過濾掉所有奇數(shù):
def is_odd(n): return n % 2 == 1?
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
11、注意字典的關(guān)鍵字也可以是一個(gè)類
12、3,?1 =?divmod(7,?2)
直接獲得商和余數(shù)
13、is函數(shù)
判斷字符是否是數(shù)字 s.isdigit()
判斷是否是小寫字母 s.islower(0
判斷變量(對象)的類型?isinstance (a, int)
14、bit_count()
3.10版本以后更新的函數(shù),可以直接計(jì)算數(shù)的二進(jìn)制的1的為數(shù),方便計(jì)算信息距離
15、獲取最低的為1的冪次
(x) & (-x)
16、re.split
leetcode 819
當(dāng)有多個(gè)切割符的時(shí)候,str.split就不行了
https://blog.csdn.net/weixin_37804469/article/details/106887991
兩個(gè)以上切割符放到'[ ]'這個(gè)里面
n = 'sssksssdsss'
print(re.split(r'[kd]', n)) #?['sss', 'sss', 'sss']
17、random的用法
randint(0,n) #在0-n中隨機(jī)取一個(gè)值
randrange(n) #在0-n-1中隨機(jī)取一個(gè)值
# 偽隨機(jī)數(shù)當(dāng)制定了random.seed()后,隨機(jī)的結(jié)果就是確定的,當(dāng)不指定seed時(shí),使用當(dāng)前時(shí)間作為seed
https://docs.python.org/zh-cn/3/library/random.html
18、二分查找
bisect.bisect_left(list, num) #在list中查找num的索引
bisect.insort_left(list, num) #在list中插入num,放入值的左側(cè)
19、反轉(zhuǎn)矩陣
grid_new?=?[list(g)?for?g?in?zip(*grid)] # 883
20、pairwise
以窗口大小為2重新組織列表
# Python 3.10 新特性
20、有序字典
from sortedcontainers import SortedDict
i = self.booked.bisect_left(end)
大于等于end的標(biāo)號
21、創(chuàng)建枚舉類
from enum import Enum
class Week(Enum):
? ? monday = 1
22、得到一個(gè)二進(jìn)制數(shù)第一個(gè)為1的位置
x = x1&-x1