# coding=utf-8 ################# # # # 内置函数 # # # ################# __author__ = 'liuyb' ########## # filter # ########## # filter(函数过滤条件,序列),通过函数,过滤序列,默认返回列表,支持list、str、tuple、unicode def _f(x): return x % 3 == 0 or x % 5 == 0 def _f_str(x): return x in "tst" # 1.返回list def fuc_list_filter(): return filter(_f, range(2, 25)) # 2.返回tuple def fuc_tuple_filter(): return filter(_f, tuple(range(2, 25))) # 3.返回str def fuc_str_filter(): return filter(_f_str, "test") # 4.函数为空 def fuc_none_filter(): return filter(None, range(2, 25)) ####### # map # ####### # map(函数条件,序列),返回列表 等于 f(x) for x in iterable def _cube(x): return x ** 3 def _add(x, y): return x + y # 1.函数中有一个参数 def fuc_list_map(): return map(_cube, range(1, 11)) # 此函数等于上面的函数 def fuc_list_map_equal(): list = [] for x in range(1, 11): list.append(x ** 3) return list # 此函数等于上面的函数 def fuc_list_map_equal1(): return [lambda x: x**3 for x in range(1, 11)] # 2.函数中有多个参数 def fuc_moreSeq_map(): seq = range(8) return map(_add, seq, seq) # 3.函数为空 def fuc_none_map(): return map(None, range(8), range(8)) ############ # reduce() # ############ def add(x, y): return x + y # 1.fuc是一个由两个参数的函数,reduce依次从seq中取一个元素,和上一次调用fuc的结果做参数,再次调用fuc def fuc_one_reduce(): return reduce(add, range(1, 11)) # 2. fuc不能为空,为空报错 def fuc_fucNone_reduce(): return reduce(None, range(1, 11)) # 3. 参数为空,第三个参数是给定初始值,给出的参数为空时,一定要给出初始值,否则报错 def fuc_seqNone_reduce(): return reduce(add, [], 2) ########### # 列表解析 # ########### # 1.一次嵌套 def fuc_squares(): squares = [] for i in range(10): squares.append(i**2) return squares # 等于fuc_squares() def fuc_squares_equal(): return [i**2 for i in range(10)] # 等于fuc_squares() def fuc_squares_equal1(): return map(lambda i: i**2, range(10)) # 2.多次嵌套 def fuc_combs(): combs = [] for x in [1, 2, 3]: for y in [3, 1, 4]: if x != y: combs.append((x, y)) return combs # 等于fuc_combs() def fuc_combs_equal(): return [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x !=y] ########### # 嵌套列表 # ########### # 1. def fuc_matrix(): matrix =[[1, 2, 3], [4, 5, 6], [7, 8, 9]] return [[row[i] for row in matrix] for i in range(3)] # 等于 fuc_matrix() def fuc_matrix_equal(): matrix =[[1, 2, 3], [4, 5, 6], [7, 8, 9]] list = [] for i in range(3): list.append([row[i] for row in matrix]) return list # 等于 fuc_matrix() def fuc_matrix_equal1(): matrix =[[1, 2, 3], [4, 5, 6], [7, 8, 9]] list = [] for i in range(3): ap = [] for row in matrix: ap.append(row[i]) list.append(ap) return list # 返回列表,内容用tuple形式展示 def fuc_zip_matrix(): matrix =[[1, 2, 3], [4, 5, 6], [7, 8, 9]] return zip(*matrix) ####### # del # ####### def fuc_del(): a =[1, 2, 3, 4, 5, 6, 7, 8, 9] # 删除a中第0个元素,没有返回值 del a[0] print a # 删除a del a b =[1, 2, 3, 4, 5, 6, 7, 8, 9] # 删除b中第0个元素,并返回删除值 print b.pop(0) print b c = ['1', 2, 3, 4, 5, 6, 7, 8, 9] # 删除c中的具体元素"1" c.remove('1') print c if __name__ == "__main__": #print fuc_matrix_equal1() print fuc_del()
2.2 数据结构-内置函数
最新推荐文章于 2022-05-18 08:26:47 发布