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