from collections import Counter
str_1, str_2, str_3 = "acbde", "abced", "abcda"
cnt_1, cnt_2, cnt_3 = Counter(str_1), Counter(str_2), Counter(str_3)
if cnt_1 == cnt_2:
print('1 and 2 anagram')
if cnt_1 == cnt_3:
print('1 and 3 anagram')
# 输出:1 and 2 anagram
注意: 此方法对大小写敏感,如需忽略大小写,请先统一转换。
12. 使用 try-except-else-finally 模块
结构化异常处理能确保程序在出错时优雅降级,并在最后执行清理工作。
a, b = 1, 0try:
print(a / b)
# 当 b 为 0 时会抛出异常except ZeroDivisionError:
print("division by zero")
else:
print("no exceptions raised")
finally:
print("Run this always")
# 输出:# division by zero# Run this always
注意:else 块仅在无异常时执行,finally 块无论是否发生异常都会执行。
13. 使用枚举函数得到 key/value 对
enumerate() 允许在遍历列表时同时获取索引和值。
my_list = ['a', 'b', 'c', 'd', 'e']
for index, value inenumerate(my_list):
print('{0}: {1}'.format(index, value))
# 输出:# 0: a# 1: b# 2: c# 3: d# 4: e
import time
start_time = time.time()
# 待测代码for i inrange(10**5):
a, b = 1, 2
c = a + b
# 待测代码结束
end_time = time.time()
time_taken_in_micro = (end_time - start_time) * (10**6)
print(time_taken_in_micro)
# 输出示例:18770.217895507812
注意: 对于极短的代码段,建议使用 timeit 模块以获得更精确的结果。
17. 列表展开
处理嵌套列表时,可以使用递归或迭代方式将其展平为一维列表。
from iteration_utilities import deepflatten
# 如果只有一层嵌套,可使用列表推导式defflatten(l):
return [item for sublist in l for item in sublist]
l = [[1, 2, 3], [3]]
print(flatten(l))
# 输出:[1, 2, 3, 3]# 如果不知道嵌套深度,可使用第三方库
l = [[1, 2, 3], [4, [5], [6, 7]], [8, [9, [10]]]]
print(list(deepflatten(l, depth=3)))
# 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
defunique(l):
iflen(l) == len(set(l)):
print("All elements are unique")
else:
print("List has duplicates")
unique([1, 2, 3, 4])
# 输出:All elements are unique
unique([1, 1, 2, 3])
# 输出:List has duplicates