defsearch_n(s, c, n): size = 0 for i, x inenumerate(s): if x == c: size += 1 if size == n: return i return -1 print(search_n("fdasadfadf", "a", 3))# 结果为7,正确 print(search_n("fdasadfadf", "a", 30))# 结果为-1,正确
2 斐波那契数列前n项
deffibonacci(n): a, b = 1, 1 for _ inrange(n): yield a a, b = b, a + b list(fibonacci(5)) # [1, 1, 2, 3, 5]
3 找出所有重复元素
from collections import Counter
deffind_all_duplicates(lst): c = Counter(lst) returnlist(filter(lambda k: c[k] > 1, c))
find_all_duplicates([1, 2, 2, 3, 3, 3]) # [2,3]
4 联合统计次数
Counter对象间可以做数学运算
from collections import Counter
a = ['apple', 'orange', 'computer', 'orange'] b = ['computer', 'orange']
ca = Counter(a) cb = Counter(b) #Counter对象间可以做数学运算 ca + cb # Counter({'orange': 3, 'computer': 2, 'apple': 1}) # 进⼀步抽象,实现多个列表内元素的个数统计
defsumc(*c): if (len(c) < 1): return mapc = map(Counter, c) s = Counter([]) for ic in mapc: # ic 是⼀个Counter对象 s += ic return s #Counter({'orange': 3, 'computer': 3, 'apple': 1, 'abc': 1, 'face': 1}) sumc(a, b, ['abc'], ['face', 'computer'])
a = [{'date': '2023-08-04', 'weather': 'cloud'}, {'date': '2023-08-02', 'weather': 'sunny'}, {'date': '2023-08-01', 'weather': 'cloud'}] from operator import itemgetter from itertools import groupby a.sort(key=itemgetter('weather')) for k, items in groupby(a, key=itemgetter('weather')): print(k) for i in items: print(i)
from operator import itemgetter from itertools import groupby a.sort(key=itemgetter('weather', 'date')) for k, items in groupby(a, key=itemgetter('weather')): print(k) for i in items: print(i)
from math import ceil defdivide_iter(lst, n): if n <= 0: yield lst return i, div = 0, ceil(len(lst) / n) while i < n: yield lst[i * div: (i + 1) * div] i += 1 list(divide_iter([1, 2, 3, 4, 5], 0)) # [[1, 2, 3, 4, 5]] list(divide_iter([1, 2, 3, 4, 5], 2)) # [[1, 2, 3], [4, 5]]
10 列表全展开(⽣成器版)
#多层列表展开成单层列表 a=[1,2,[3,4,[5,6],7],8,["python",6],9] deffunction(lst): for i in lst: iftype(i)==list: yieldfrom function(i) else: yield i print(list(function(a))) # [1, 2, 3, 4, 5, 6, 7, 8, 'python', 6, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 'python', 6, 9]
11 测试函数运⾏时间的装饰器
#测试函数执⾏时间的装饰器⽰例 import time deftiming_func(fn): defwrapper(): start=time.time() fn() #执⾏传⼊的fn参数 stop=time.time() return (stop-start) return wrapper @timing_func deftest_list_append(): lst=[] for i inrange(0,100000): lst.append(i) @timing_func deftest_list_compre(): [i for i inrange(0,100000)] #列表⽣成式 a=test_list_append() c=test_list_compre() print("test list append time:",a) print("test list comprehension time:",c) print("append/compre:",round(a/c,3))
test list append time: 0.006039142608642578
test list comprehension time: 0.0050089359283447266
append/compre: 1.206
12 统计异常出现次数和时间的装饰器
写⼀个装饰器,统计某个异常重复出现指定次数时,经历的时长。
import time import math defexcepter(f): i = 0 t1 = time.time() defwrapper(): try: f() except Exception as e: nonlocal i i += 1 print(f'{e.args[0]}: {i}') t2 = time.time() if i == n: print(f'spending time:{round(t2-t1,2)}') return wrapper
关键词 nonlocal常⽤于函数嵌套中,声明变量i为⾮局部变量;
如果不声明, i+=1表明 i 为函数 wrapper内的局部变量,因为在 i+=1引⽤(reference)时, i 未被声明,所以会报 unreferenced variable的错误。
使⽤创建的装饰函数 excepter, n 是异常出现的次数。
共测试了两类常见的异常: 被零除 和 数组越界 。
n = 10# 除计数外 @excepter defdivide_zero_except(): time.sleep(0.1) j = 1/(40-20*2)
# 测试零除 for _ inrange(n): divide_zero_except() @excepter defoutof_range_except(): a = [1,3,5] time.sleep(0.1) print(a[3]) # 测试超出范围除外 for _ inrange(n): outof_range_except()
division by zero: 1
division by zero: 2
division by zero: 3
division by zero: 4
division by zero: 5
division by zero: 6
division by zero: 7
division by zero: 8
division by zero: 9
division by zero: 10
spending time:1.09
list index out of range: 1
list index out of range: 2
list index out of range: 3
list index out of range: 4
list index out of range: 5
list index out of range: 6
list index out of range: 7
list index out of range: 8
list index out of range: 9
list index out of range: 10
spending time:1.09
打印出来的结果如下:
division by zero: 1 division by zero: 2 division by zero: 3 division by zero: 4 division by zero: 5 division by zero: 6 division by zero: 7 division by zero: 8 division by zero: 9 division by zero: 10 spending time:1.09 list index out of range: 1 list index out of range: 2 list index out of range: 3 list index out of range: 4 list index out of range: 5 list index out of range: 6 list index out of range: 7 list index out of range: 8 list index out of range: 9 list index out of range: 10 spending time:1.09
13 测试运⾏时长的装饰器
#测试函数执⾏时间的装饰器⽰例 import time deftiming(fn): defwrapper(): start=time.time() fn() #执⾏传⼊的fn参数 stop=time.time() return (stop-start) return wrapper @timing deftest_list_append(): lst=[] for i inrange(0,100000): lst.append(i) @timing deftest_list_compre(): [i for i inrange(0,100000)] #列表⽣成式 a=test_list_append() c=test_list_compre() print("test list append time:",a) print("test list comprehension time:",c) print("append/compre:",round(a/c,3))
test list append time: 0.008554697036743164
test list comprehension time: 0.004532337188720703
append/compre: 1.887
这个实例与测试函数执⾏时长的装饰器是一样的
14 装饰器通俗理解
再看⼀个装饰器:
defcall_print(f): defg(): print('you\'re calling %s function'%(f.__name__,)) return g