内置函数
range()
从后往前遍历到0:
for i in range(length - 1, -1, -1):
先列再行:
dp = [[0]*(len2 + 1) for _ in range(len1 + 1)]
dp = [[0 for _ in range(len2 + 1)] for _ in range(len1 + 1)]
sort()与sorted()
nums = [2,6,3,8,4]
string = 'sdfggsma'
str_list = ['abc','abcd','abca']
print(sorted(nums)) # 不改变原数组顺序,需要赋值给一个新变量
print(nums)
nums.sort() # 改变原数组顺序
print(nums)
print(sorted(str_list)) # 均可以对字符数组排序
print(str_list)
str_list.sort()
print(str_list)
print(sorted(string)) # 可以对字符排序
# string.sort() # 不可以对字符排序
# print(string)
输出结果:
[2, 3, 4, 6, 8]
[2, 6, 3, 8, 4]
[2, 3, 4, 6, 8]
['abc', 'abca', 'abcd']
['abc', 'abcd', 'abca']
['abc', 'abca', 'abcd']
['a', 'd', 'f', 'g', 'g', 'm', 's', 's']
stones = sorted(zip(rocks, capacity), key=lambda x: (x[1] - x[0])) # 自定义排序函数
stockPrices.sort(key=lambda x: x[0]) # 二维数组按照第0列排序
# 先按第一列降序,再按第二列升序排列
people.sort(key = lambda x:(-x[0],x[1]))
# 将nums按绝对值从大到小排列,两种方法都可以
nums = sorted(nums, key = abs, reverse = True)
nums.sort(key = abs,reverse = True)
sum()
对数组求和
left_count = sum(1 for i in range(lo, hi + 1) if nums[i] == left)
sum_ = sum(nums)
decimal.Decimal()
高精度(默认28位,可调更高)
import decimal
斜率 = decimal.Decimal(y1-y0)/decimal.Decimal(x1-x0)
6076. 表示一个折线图的最少线段数
zip()
for x, y in zip(capacity, rocks)
split()
默认会将字符串用空白或者换行符分割,并且返回一个列表
注意:字符串中间无论有多少个空格,它都会按一个空白进行分割。
s = '1 2 3 4 5 6'
a = s.split(' ')
# 输出:['1', '2', '3', '4', '5', '', '', '', '6']
strip()
默认将字符串首部与尾部的空白去掉,但不会去除字符串中间的空格,返回一个字符串
s = ' 1 2 3 4 5 6'
b = s.strip()
# 输出:'1 2 3 4 5 6'
Counter()
from collections import Counter
类似于hashmap计算数组中每个元素出现的次数
AABBBC -> {'A':2,'B':3,'C':1}
与dict()数据的区别是Counter()函数默认没有key的value为0
6083. 判断一个数的数字计数是否等于数位的值
class Solution:
def digitCount(self, num: str) -> bool:
cnter = Counter(num)
for i in range(len(num)):
if cnter[str(i)] != int(num[i]):
return False
return True
class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
dict_freq = list(collections.Counter(tasks).values()) # 所有任务的出现次数, AABBBC -> [2,3,1]
max_freq = max(dict_freq) # 最多的执行次数
max_num = dict_freq.count(max_freq) # 具有最多执行次数的任务数量
return max((max_freq - 1) * (n + 1) + max_num, len(tasks))
class Solution:
def totalFruit(self, fruits: List[int]) -> int:
left, right, res = 0, 0, 0
dic = Counter()
while right < len(fruits):
dic[fruits[right]] += 1
while len(dic) > 2:
dic[fruits[left]] -= 1
if dic[fruits[left]] == 0:
del dic[fruits[left]]
left += 1
right += 1
res = max(res, right - left)
return res
Counter()函数可以直接相减
若ransomNote中的字符在magazine没有出现则会返回Counter({'a': 1})
否则返回Counter(),即为空的
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
if len(ransomNote) > len(magazine):
return False
return not Counter(ransomNote) - Counter(magazine)
count()
string = 'banana pie banana'
string.count('a',2)
输出:5
enumerate()
class Solution:
def largestWordCount(self, messages: List[str], senders: List[str]) -> str:
# 统计每个sender的发送量
cnt = defaultdict(int)
for i,mes in enumerate(messages):
cnt[senders[i]]+=len(mes.split(' '))
tmp = []
# 找到发出信息最多的人(可以有多个)
maximum = max(cnt.values())
for k,v in cnt.items():
if v == maximum:
tmp.append(k)
# 字典序排序找到最大的
tmp.sort(reverse=True)
return tmp[0]
isdigit()、isdecimal()、isnumeric()
都可以用来判断字符或字符串是否是数字
num = "1" #unicode
num.isdigit() # True
num.isdecimal() # True
num.isnumeric() # True
num = "1" # 全角
num.isdigit() # True
num.isdecimal() # True
num.isnumeric() # True
num = b"1" # byte
num.isdigit() # True
num.isdecimal() # AttributeError 'bytes' object has no attribute 'isdecimal'
num.isnumeric() # AttributeError 'bytes' object has no attribute 'isnumeric'
num = "IV" # 罗马数字
num.isdigit() # True
num.isdecimal() # False
num.isnumeric() # True
num = "四" # 汉字
num.isdigit() # False
num.isdecimal() # False
num.isnumeric() # True
===================
区别:
isdigit()
True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字
False: 汉字数字
Error: 无
isdecimal()
True: Unicode数字,,全角数字(双字节)
False: 罗马数字,汉字数字
Error: byte数字(单字节)
isnumeric()
True: Unicode数字,全角数字(双字节),罗马数字,汉字数字
False: 无
Error: byte数字(单字节)
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
s = sentence.split(' ')
for i in range(len(s)):
c = s[i]
# print(c)
if len(c)>1 and c[0]=='$' and all(t.isdigit() for t in c[1:]):
cost = int(c[1:])
newc = '$'+f'{cost*(1-discount/100):.2f}'
# print(newc,"----")
s[i]=newc
return ' '.join(s)
class Solution:
def discountPrices(self, sentence: str, discount: int) -> str:
l = sentence.split(' ')
r = []
for x in l:
if x[0] == '$' and x[1:].isnumeric():
i = int(x[1:]) * (100 - discount)
r.append('$%d.%02d' % (i // 100, i % 100))
else:
r.append(x)
return ' '.join(r)
pairwise()
判断两个相邻的字符是否相同
for s, t in pairwise(password):
if s == t:
return False
ord()
取字符的ASCII值
for i in range(len(s)):
hash_[ord(s[i]) - ord('a')] = i
iloc() ilx() loc()
参考资料:
Python中 isdigit() 和 isnumeric() 的区别
Python 基础API