from random import randint #### 带有默认值的参数 l1 = [i for i in range(1, 10)] l2 = [i for i in range(10, 20)] ##print("l1 =", l1) ##print("l2 =", l2) ##def accum(lst, init=0): ## nsum = init ## for x in lst: ## nsum += x ## return nsum ## ##a = accum(l1) ##b = accum(l2, a) ##print(a, b) ##def accum1(lst, init=0, num=-1): ## nsum = init ## if num < 0: ## num = len(lst) ## for i in range(num): ## nsum += lst[i] ## return nsum ## ##a = accum1(l1, 31) ##b = accum1(l1, 10, 6) ##c = accum1(l1, num=6) ##print(a, b, c) #### 函数形参和调用时实参的一些情况 ##def func(a, *b, c=0, d=1): ## print(a, b, c, d) ## return 0 ## ##func(1, 2, 3, d=10) ##func(1) ##def func(a, b=0, *c, d=11): ## print(a, b, c, d) ## return 0 ## ##func(1, 2, 3, 4, 5) ##func(1, 2, 3, d=10) ##func(1) #### 表构造和变动性 ##list1 = [0] * 10 ##list10 = list1.copy() ##list2 = [[]] * 10 ##list20 = list2.copy() ##list3 = [[] for i in range(10)] ##list30 = list3.copy() ##list1[1] = 3 ##list2[1].append(1) ##list3[1].append(1) #### 函数的带默认值的参数,变动对象引起的共享 ##def insert(args, start=[]): ## for x in args: ## start.append(x) ## return start ## ##t1 = (1, 2, 3, 4) ##print(t1) ##t2 = [randint(1, 20) for i in range(10)] ##print(t2) ## ##list1 = insert(t1) ##print(list1) ##list2 = insert(t2) ##print(list1) ##print(list2) ### 一个简单生成器 ##def nat(limit): ## for n in range(limit): ## yield n ## ##for i in nat(10): ## print(i) ### 在生成器中可以混合使用 yield and return ### 注意: 生成器的返回值对循环的迭代没有影响 ##def nat(limit): ## n = 0 ## while True: ## n += 1 ## if n > limit: ## return n ## yield n ## ##for i in nat(10): ## print(i) ### 一个生成器:生成参数表中所有正数 ##def positive(lst): ## for x in lst: ## if (isinstance(x, int) or isinstance(x, float)) and x > 0.0: ## yield x ## ##ll = [1, "abc", -0.3, -2, 3.12, 0, 2, 1.27, 5] ##for x in positive(ll): ## print(x) ##print() ##for x in filter(lambda x: (isinstance(x, int) or ## isinstance(x, float)) and x > 0.0, ## ll): ## print(x) #### 生成直至 n 的Fibonacci数 ##def gen_fib(n): ## n1 = 0 ## n2 = 1 ## for i in range(n+1): ## yield n2 ## n1, n2 = n2, n1+n2 ## ##for n in gen_fib(10): ## print(n) ### An infinite generator ##def gen_fibs(): ## n1 = 0 ## n2 = 1 ## while True: ## yield n2 ## n1, n2 = n2, n1+n2 ## ##fib = gen_fibs() ##for i in range(20): ## print(fib.__next__()) ### A generator to yield elements of a list circularly ##def circular(seq): ## i = 0 ## while True: ## yield seq[i] ## i = (i + 1) % len(seq) ##for i in range(0, 150, 13): ## print(str(i).rjust(3), str(i**2).rjust(5), str(i**3).rjust(7)) #### 格式化实例 ##print("abc{0:->10s}123".format("hhhhh"), "\n") ## ##print("price:{price:8.2f}, quantity:{quantity:4d}".format( ## quantity=23, price=1389.99), ## "\n") ## ##print("abc{:<<10d}123".format(55555))