学习日记2025.7.17
错题记录:
错 --> 正
1.
.append[] --> .append()
str.sort() --> sorted(str)
Python 字符串本身没有 sort() 方法,因为字符串是不可变的。但是,可以使用 sorted() 函数对字符串进行排序,并将其转换成一个字符列表。如果需要将排序后的字符列表重新组合成字符串,可以使用 join() 方法:
"".join(sorted(str))
plus: 对列表操作时.sort()直接在原列表上修改,没有返回值,而sorted()会返回排序后的列表
2.
dict()和defaultdict()的区别
temp = dict() if i not in temp.keys(): temp[i].append(i) --> temp = defaultdict()
当字典中不存在某个键时,用dict()直接调用会报错KeyError,而defaultdict()会自动创建不会报错。
以下两种写法作用相同:
temp = dict()
if "1" not in temp.keys():
temp["1"] = 1
print(temp["1"])
from collections import defaultdict
temp = defaultdict()
temp["1"] = 1
print(temp["1"])
1
1

浙公网安备 33010602011771号