Python基础课:内置函数对列表的操作
1 >>> x = list(range(10)) 2 >>> import random 3 >>> random.shuffle(x) #打乱顺序 4 >>> x 5 [2, 4, 5, 9, 3, 7, 8, 0, 6, 1] 6 >>> max(x) #返回最大值 7 9 8 >>> min(x) #返回最小值 9 0 10 >>> sum(x) #所有元素之和 11 45 12 >>> len(x) #所有元素个数 13 10 14 >>> list(zip(x,[1]*10)) #多列表重新组合 15 [(2, 1), (4, 1), (5, 1), (9, 1), (3, 1), (7, 1), (8, 1), (0, 1), (6, 1), (1, 1)] 16 >>> list(zip(range(1,4))) #zip()函数可以用于一个序列或者迭代对象 17 [(1,), (2,), (3,)] 18 >>> list(zip(['a','b','c'],[1,2])) #两个列表不等长,以短的为准 19 [('a', 1), ('b', 2)] 20 >>> enumerate(x) #枚举列表元素,返回enumerate对象 21 <enumerate object at 0x0000016166A057E0> 22 >>> list(enumerate(x)) #enumerate对象可迭代 23 [(0, 2), (1, 4), (2, 5), (3, 9), (4, 3), (5, 7), (6, 8), (7, 0), (8, 6), (9, 1)] 24 >>> x 25 [2, 4, 5, 9, 3, 7, 8, 0, 6, 1]
1 >>> list(map(str,range(5))) #转换为字符串 2 ['0', '1', '2', '3', '4'] 3 >>> def add5(v): 4 return v+5 5 6 >>> list(map(add5,range(10))) #将单参数函数映射到所有元素 7 [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] 8 >>> def add(x,y): 9 return x+y 10 11 >>> list(map(add,range(5),range(5,10))) #将双参数函数映射到两个序列上 12 [5, 7, 9, 11, 13] 13 >>> list(map(lambda x,y:x+y, range(5), range(5,10))) 14 [5, 7, 9, 11, 13] 15 >>> [add(x,y) for x, y in zip(range(5), range(5,10))] 16 [5, 7, 9, 11, 13] 17 >>>
1 #标准库functools中的reduce()可以将一个接受2个参数的函数以累积的方式从左到右一次作用到一个序列或迭代器对象的所有元素上 2 >>> from functools import reduce 3 >>> seq = [1,2,3,4,5,6,7,8,9] 4 >>> reduce(lambda x, y:x+y,seq) 5 45 6 >>>
1 >>> seq = ['foo','x33','?!','***'] 2 >>> def func(x): 3 return x.isalnum() #测试是否为字母或者数字 4 >>> filter(func, seq) #返回filter对象 5 <filter object at 0x000001B376088BA8> 6 >>> list(filter(func,seq)) #将filter对象转换为list 7 ['foo', 'x33'] 8 >>> seq 9 ['foo', 'x33', '?!', '***'] 10 >>> [x for x in seq if x.isalnum()] #用列表推导式实现相同功能 11 ['foo', 'x33'] 12 >>> list(filter(lambda x:x.isalnum(),seq)) #用lambda实现相同功能 13 ['foo', 'x33'] 14 >>> list(filter(None,[1,2,3,0,0,4,0,5])) #指定函数为None 15 [1, 2, 3, 4, 5] 16 >>>
1 >>> import random 2 >>> x = [random.randint(1,100) for i in range(10)] #生成10个1-100区间的随机数 3 >>> x 4 [72, 11, 80, 97, 94, 75, 70, 21, 21, 41] 5 >>> list(map(lambda i:i+5, x)) #所有元素加5 6 [77, 16, 85, 102, 99, 80, 75, 26, 26, 46] 7 >>> x = [random.randint(1,10) for i in range(10)] 8 >>> x 9 [5, 7, 6, 2, 6, 1, 5, 1, 2, 7] 10 >>> y = [random.randint(1,10) for i in range(10)] 11 >>> y 12 [2, 10, 9, 7, 7, 4, 9, 1, 7, 1] 13 >>> import operator 14 >>> sum(map(operator.mul, x, y)) #向量内积 15 261 16 >>> sum((i*j for i,j in zip(x,y))) #使用内置函数计算向量内积 17 261 18 >>> list(map(operator.add, x, y)) #两个等长的向量对应元素相加 19 [7, 17, 15, 9, 13, 5, 14, 2, 9, 8] 20 >>> list(map(lambda i,j: i+j, x,y)) #使用lambda实现同样功能 21 [7, 17, 15, 9, 13, 5, 14, 2, 9, 8] 22 >>>