更多精彩內(nèi)容,請關(guān)注【力扣簡單題】。
計(jì)數(shù)器
如果我們想統(tǒng)計(jì)列表或字符串中每個(gè)元素出現(xiàn)的次數(shù),我們可以這樣做:
def counter(l):
count_dict = {}
for e in l:
if e in count_dict.keys():
count_dict[e] += 1
else:
count_dict[e] = 1
return count_dict
s = "apple"
c = counter(s)
print(c)
# {'a': 1, 'p': 2, 'l': 1, 'e': 1}
如果我們使用collection模塊中的Counter,就可以快速進(jìn)行統(tǒng)計(jì):
from collections import Counter
s = "apple"
c = Counter(s)
print(c)
# Counter({'p': 2, 'a': 1, 'l': 1, 'e': 1})
列表也是可以統(tǒng)計(jì)的。
生成的Counter類可以看做一個(gè)字典,相當(dāng)于字典的繼承,支持加減操作,例如:
l1 = [7, 7, 7, 7, 8, 8, 8]
l2 = [7, 7, 7, 8, 8, 8, 8, 9]
c1, c2 = Counter(l1), Counter(l2)
print(c1+c2)
# Counter({7: 7, 8: 7, 9: 1})
print(c1-c2)
# Counter({7: 1})
排列組合
一個(gè)箱子里有寫著1, 2, 3, 4的四張卡片,從中任意抽兩張:
不考慮先后順序,求所有可能的組合,需要使用combinations;
考慮先后順序,且無放回的抽取,需要使用permutations;
考慮先后順序,且有放回的抽取,需要使用product;
實(shí)驗(yàn)效果:
from itertools import product, combinations, permutations
nums = [1, 2, 3, 4]
c = combinations(nums, r=2)
a = permutations(nums, r=2)
p = product(nums, repeat=2)
print(list(c))
# [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
print(list(a))
# [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
print(list(p))
# [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]
數(shù)學(xué)計(jì)算
有時(shí)候,我們需要用到數(shù)學(xué)計(jì)算包,例如計(jì)算平方,對數(shù)等情況,數(shù)學(xué)計(jì)算包可以大大提高我們的編程效率。
from math import log, sqrt, pow
print(log(16, 2))
# 4
print(sqrt(2))
# 1.4142135623730951
print(pow(2, 6))
# 64.0
二分查找
幫助我們使用二分查找法快速定位元素在排序數(shù)組中的位置,或應(yīng)該插入排序數(shù)組的位置。
import bisect
print(bisect.bisect_left([1, 2, 3, 4, 5], 2))
# 1
print(bisect.bisect_left([1, 2, 3, 4, 5], 3.5))
# 3
print(bisect.bisect_right([1, 2, 3, 4, 5], 3.5))
# 4
print(bisect.bisect_left([1, 2, 3, 4, 5], 5.5))
# 5
print(bisect.bisect_right([1, 2, 3, 4, 5], 5.5))
# 5
l = [1, 2, 3, 4, 5]
l.insert(bisect.bisect(l, 3.3), 3.3)
print(l)
# [1, 2, 3, 3.3, 4, 5]
靈活使用上述擴(kuò)展包,會(huì)使我們的編碼變得高效。
如有疑問或建議,歡迎評論區(qū)留言~